# retoor <retoor@molodetz.nl>

from devplacepy.cli._shared import _audit_cli


def cmd_attachments_prune(args):
    from datetime import datetime, timezone, timedelta
    from devplacepy.database import db
    from devplacepy.attachments import delete_attachment

    if "attachments" not in db.tables:
        print("Attachments table does not exist")
        return

    cutoff = (datetime.now(timezone.utc) - timedelta(hours=args.hours)).isoformat()
    orphans = [
        att
        for att in db["attachments"].find(target_type="", target_uid="")
        if att.get("created_at", "") < cutoff
    ]
    for att in orphans:
        delete_attachment(att["uid"])
    _audit_cli(
        "cli.attachments.prune",
        f"CLI pruned {len(orphans)} orphan attachments",
        metadata={"count": len(orphans), "hours": args.hours},
    )
    print(f"Pruned {len(orphans)} orphan attachment(s) older than {args.hours}h")


def register_attachments(subparsers):
    attachments = subparsers.add_parser("attachments", help="Attachment management")
    att_sub = attachments.add_subparsers(title="action", dest="action")
    att_prune = att_sub.add_parser(
        "prune", help="Remove orphaned attachment records and files"
    )
    att_prune.add_argument(
        "--hours",
        type=int,
        default=24,
        help="Only prune orphans older than this many hours",
    )
    att_prune.set_defaults(func=cmd_attachments_prune)
