"""Delete generated report files older than a retention threshold.

Standards: ISO 27001 A.8.3 (disposal), NIST SP 800-88 (sanitization).
Regenerable artifacts only. The database holds the source of truth.
Default retention: 7 days (weekly). Deletions are logged append-only.
"""
import json
from datetime import datetime, timedelta, timezone
from pathlib import Path

from django.conf import settings
from django.core.management.base import BaseCommand
from django.core.management import call_command


RETENTION_DIRS = ["daily_reports", "weekly_reports", "parent_reports", "result_cards"]


class Command(BaseCommand):
    help = "Delete report files older than --days. Append-only audit log."

    def add_arguments(self, parser):
        parser.add_argument("--days", type=int, default=7)
        parser.add_argument("--dry-run", action="store_true")

    def handle(self, *args, **options):
        days = options["days"]
        dry = options["dry_run"]
        cutoff = datetime.now(timezone.utc) - timedelta(days=days)
        base = Path(settings.BASE_DIR).parent / "output"
        deleted = []
        kept = 0
        for d in RETENTION_DIRS:
            folder = base / d
            if not folder.is_dir():
                continue
            for f in folder.iterdir():
                if not f.is_file():
                    continue
                mtime = datetime.fromtimestamp(f.stat().st_mtime, tz=timezone.utc)
                if mtime >= cutoff:
                    kept += 1
                    continue
                entry = {"path": str(f), "size": f.stat().st_size, "mtime": mtime.isoformat()}
                if dry:
                    self.stdout.write("WOULD DELETE " + str(f))
                else:
                    f.unlink()
                    deleted.append(entry)
                    self.stdout.write("deleted " + str(f))
        self.stdout.write(self.style.SUCCESS("Deleted: " + str(len(deleted)) + " kept: " + str(kept)))
        if not dry and deleted:
            log_path = Path(settings.BASE_DIR).parent / "tmp" / "cleanup_log.jsonl"
            log_path.parent.mkdir(parents=True, exist_ok=True)
            with log_path.open("a", encoding="utf-8") as fh:
                fh.write(json.dumps({"ts": datetime.now(timezone.utc).isoformat(), "days": days, "deleted": deleted}) + "\n")
            self.stdout.write("log: " + str(log_path))

        # Section 11.7: enforce SessionEvent (90d) and LoginAttempt (30d)
        # retention in the same cron run. Standards: ISO 27001 A.8.10;
        # ISO 27701 7.4.5. Independent command, invoked here so the
        # cron entry stays unchanged (Rule 3).
        self.stdout.write("")
        self.stdout.write("--- sessions_purge ---")
        call_command("sessions_purge", dry_run=dry)
        # Rule 18: kill-switch self-test chain (Google SRE Ch.14)
        try:
            call_command("killswitch_selftest")
        except Exception:
            pass

