"""Deep weekly cleanup + disk report. Dry-run default."""
import json, shutil
from datetime import datetime, timezone
from pathlib import Path
from django.conf import settings
from django.core.management.base import BaseCommand

class Command(BaseCommand):
    help = "Deep weekly cleanup + disk report."
    def add_arguments(self, p):
        p.add_argument("--apply", action="store_true")
    def handle(self, *a, **o):
        ap = o["apply"]; b = Path(settings.BASE_DIR).parent
        n = datetime.now(timezone.utc); acts = []
        tot, used, free = shutil.disk_usage(str(b))
        print("disk: used=" + str(round(used/1e9,2)) + "GB free=" + str(round(free/1e9,2)) + "GB")
        bk = list((b/"backups").glob("*.tar.gz"))
        print("backups: " + str(len(bk)) + " tarball(s)")
        for f in (b/"tmp").glob("*.jsonl"):
            try:
                if (n - datetime.fromtimestamp(f.stat().st_mtime, timezone.utc)).days >= 90:
                    acts.append(str(f))
            except OSError: pass
        log = b/"tmp"/"clean_weekly_log.jsonl"
        log.parent.mkdir(parents=True, exist_ok=True)
        with log.open("a") as fh:
            fh.write(json.dumps({"ts": n.isoformat(), "apply": ap, "n": len(acts), "free_gb": round(free/1e9,2)}) + chr(10))
        print(("APPLY" if ap else "DRY-RUN") + ": " + str(len(acts)) + " actions")
        for x in acts[:20]: print("  " + x)
