# retoor <retoor@molodetz.nl>

from devplacepy.cli._shared import _audit_cli


def cmd_accounts_prune(args):
    from devplacepy.services.moderation import deletion

    pending = deletion.due_purges()
    if args.dry_run:
        for row in pending:
            print(f"{row['uid']} deleted at {row['deletion_requested_at']}")
        print(f"{len(pending)} account(s) due for purge")
        return
    purged = deletion.purge_due()
    _audit_cli(
        "cli.accounts.prune",
        f"CLI purged {purged} deleted account(s) past the grace window",
        metadata={"count": purged},
    )
    print(f"Purged {purged} deleted account(s)")


def cmd_accounts_pending(args):
    from devplacepy.services.moderation import deletion

    pending = deletion.due_purges()
    for row in pending:
        print(f"{row['uid']}\t{row['deletion_requested_at']}")
    print(f"{len(pending)} account(s) past the {deletion.grace_hours()}h grace window")


def register_accounts(subparsers):
    accounts = subparsers.add_parser("accounts", help="Deleted account management")
    accounts_sub = accounts.add_subparsers(title="action", dest="action")
    prune = accounts_sub.add_parser(
        "prune", help="Permanently purge accounts past the deletion grace window"
    )
    prune.add_argument(
        "--dry-run", action="store_true", help="List what would be purged and exit"
    )
    prune.set_defaults(func=cmd_accounts_prune)
    pending = accounts_sub.add_parser(
        "pending", help="List deleted accounts awaiting their purge"
    )
    pending.set_defaults(func=cmd_accounts_pending)
