"""Light daily cleanup. 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 = "Light cleanup."
    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 = []
        for f in b.glob("tmp/*.bak_*"):
            try:
                if (n - datetime.fromtimestamp(f.stat().st_mtime, timezone.utc)).days >= 7:
                    acts.append(str(f))
                    if ap: f.unlink()
            except OSError: pass
        for d in (b/"api").rglob("__pycache__"):
            try:
                if (n - datetime.fromtimestamp(d.stat().st_mtime, timezone.utc)).days >= 7:
                    acts.append(str(d))
                    if ap: shutil.rmtree(d, ignore_errors=True)
            except OSError: pass
        log = b/"tmp"/"clean_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)}) + chr(10))
        print(("APPLY" if ap else "DRY-RUN") + ": " + str(len(acts)) + " actions")
        for x in acts[:20]: print("  " + x)
