"""obol prune - clean old local audit logs."""
import os
import time


def setup_parser(subparsers):
    p = subparsers.add_parser("prune", help="Clean old local audit logs")
    p.add_argument("--older-than", type=int, default=90, help="Delete logs older than N days (default: 90)")
    p.add_argument("--dry-run", action="store_true", help="Show what would be deleted without deleting")
    p.add_argument("--force", action="store_true", help="Skip confirmation prompt")
    p.set_defaults(func=cmd_prune)


def cmd_prune(args):
    audit_dir = os.path.expanduser("~/.obol/audit")
    if not os.path.isdir(audit_dir):
        print("No audit logs found (~/.obol/audit/ does not exist)")
        return

    threshold_days = args.older_than
    threshold_secs = threshold_days * 86400
    now = time.time()
    dry_run = args.dry_run
    force = args.force

    # Scan for old files
    old_files = []
    total_size = 0
    total_files = 0

    for filename in os.listdir(audit_dir):
        if not filename.endswith(".jsonl"):
            continue
        filepath = os.path.join(audit_dir, filename)
        if not os.path.isfile(filepath):
            continue
        total_files += 1
        mtime = os.path.getmtime(filepath)
        age_days = (now - mtime) / 86400
        if age_days > threshold_days:
            size = os.path.getsize(filepath)
            old_files.append((filepath, filename, size, age_days))
            total_size += size

    if not old_files:
        print(f"No audit logs older than {threshold_days} days.")
        print(f"Total files in ~/.obol/audit/: {total_files}")
        return

    # Format size nicely
    def fmt_size(b):
        if b < 1024:
            return f"{b} B"
        if b < 1024 * 1024:
            return f"{b / 1024:.1f} KB"
        return f"{b / 1024 / 1024:.1f} MB"

    print(f"Found {len(old_files)} log file(s) older than {threshold_days} days")
    print(f"Total size: {fmt_size(total_size)}")
    print(f"Total files in ~/.obol/audit/: {total_files}")
    print()

    # Show files
    for filepath, filename, size, age_days in sorted(old_files, key=lambda x: x[3], reverse=True):
        print(f"  {filename}  ({fmt_size(size)}, {int(age_days)} days old)")
    print()

    if dry_run:
        print("Dry run - no files deleted.")
        return

    if not force:
        try:
            answer = input(f"Delete {len(old_files)} file(s)? [y/N] ")
            if answer.lower() not in ("y", "yes"):
                print("Cancelled.")
                return
        except (EOFError, KeyboardInterrupt):
            print("\nCancelled.")
            return

    # Delete
    deleted = 0
    for filepath, filename, size, age_days in old_files:
        try:
            os.unlink(filepath)
            deleted += 1
        except OSError as e:
            print(f"  Failed to delete {filename}: {e}")

    print(f"Deleted {deleted}/{len(old_files)} file(s), freed {fmt_size(total_size)}")
