#!/usr/bin/python3.11
"""Preview or explicitly confirm a complete rootful container-state purge."""
import argparse
import json
import os
import sys
import time
from mykos_prune import plan, queue, status, execute


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('action', nargs='?', choices=['plan', 'purge', 'status'], default='plan')
    parser.add_argument('--dry-run', action='store_true', help='Print the plan without changing anything')
    parser.add_argument('--worker', action='store_true', help=argparse.SUPPRESS)
    args = parser.parse_args()
    if os.geteuid() != 0: parser.error('Root required')
    if args.worker:
        if args.action != 'plan' or args.dry_run: parser.error('Invalid worker arguments')
        result = execute()
    elif args.action == 'status': result = status()
    elif args.action == 'plan' or args.dry_run: result = plan()
    else:
        preview = plan(); print(json.dumps(preview, indent=2), flush=True)
        if not sys.stdin.isatty(): parser.error('Interactive confirmation required; use the admin API for automation')
        confirmation = input('\nThis permanently deletes the listed container state. Type ' + preview['confirmation'] + ': ')
        result = queue(confirmation)
        print('Purge queued. Stopping guests and deleting state; this may take several minutes.', flush=True)
        while result['state'] in ('queued', 'running'):
            time.sleep(2)
            result = status()
        if result['state'] != 'done':
            raise RuntimeError(json.dumps(result, indent=2))
    print(json.dumps(result, indent=2))


if __name__ == '__main__':
    try: main()
    except (ValueError, RuntimeError, OSError) as error: raise SystemExit(str(error))
