"""Session hygiene: scheduled archive + health snapshot.

Teacher directive (2026-10-15): regular event/doc updates + regular cleanup.

What it does, in order:
  1. Move .bak_* files older than 24h from prod api/ and sandbox api/ to
     archive/hygiene_<ts>/ with MANIFEST.json (Rule 9 - archive, do not delete).
  2. Run kernel_verify (both envs).
  3. Run verify_parity.sh.
  4. Append a one-line summary to today's SESSION-*-CHAT.md.
  5. Write tmp/hygiene_<ts>.json.

Idempotent. Safe to run repeatedly. --dry-run shows what would move.

Standards: ISO 15489-1:2016 9; NIST SP 800-34 Rev.1 5.3; Rule 9, 23, 28, 32;
OP-5; Guide 29.1.
"""
import json, os, shutil, subprocess, hashlib, time
from datetime import datetime, timezone
from pathlib import Path

from django.core.management.base import BaseCommand


HOME = Path.home()
IDEALOGY = HOME / "idealogy"
SANDBOX  = HOME / "idealogy_sandbox"
PROD_API = IDEALOGY / "api"
SB_API   = SANDBOX / "api"
ARCHIVE  = IDEALOGY / "archive"
TMP      = IDEALOGY / "tmp"
GUIDES   = IDEALOGY / "guides"

SKIP_PARTS = {".git", "__pycache__", "archive", "backups", "staticfiles", "media", "node_modules"}
AGE_SECONDS = 24 * 3600


def _md5(p):
    with open(p, "rb") as f: return hashlib.md5(f.read()).hexdigest()


def _is_bak(name):
    return ".bak_" in name or name.endswith(".bak")


def _skip(path):
    return any(part in SKIP_PARTS for part in path.parts)


def _find_baks(root):
    found = []
    if not root.exists(): return found
    for dirpath, dirnames, filenames in os.walk(root):
        p = Path(dirpath)
        if _skip(p):
            dirnames[:] = []
            continue
        for fn in filenames:
            if _is_bak(fn):
                full = p / fn
                if _skip(full): continue
                found.append(full)
    return found


class Command(BaseCommand):
    help = "Session hygiene: archive old .bak files, snapshot health, log."

    def add_arguments(self, parser):
        parser.add_argument("--dry-run", action="store_true",
                            help="Show what would move; do not write.")

    def handle(self, *args, **opts):
        dry = opts["dry_run"]
        now = datetime.now(timezone.utc)
        ts = now.strftime("%Y%m%d_%H%M%S")
        cutoff = time.time() - AGE_SECONDS

        report = {
            "ran_at": now.isoformat(),
            "dry_run": bool(dry),
            "archived": [],
            "kept_fresh": 0,
            "kernel_verify": {},
            "parity": {},
        }

        candidates = []
        for root in [PROD_API, SB_API]:
            for full in _find_baks(root):
                try: mt = full.stat().st_mtime
                except OSError: continue
                if mt < cutoff:
                    candidates.append((full, mt))
                else:
                    report["kept_fresh"] += 1

        if candidates and not dry:
            arc = ARCHIVE / f"hygiene_{ts}"
            arc.mkdir(parents=True, exist_ok=True)
            manifest = []
            for full, mt in candidates:
                rel = full.relative_to(HOME)
                dst = arc / rel
                dst.parent.mkdir(parents=True, exist_ok=True)
                m = _md5(full); size = full.stat().st_size
                shutil.move(str(full), str(dst))
                manifest.append({"rel": str(rel), "md5": m, "size": size,
                                 "mtime": datetime.fromtimestamp(mt, tz=timezone.utc).isoformat()})
            with open(arc / "MANIFEST.json", "w") as f:
                json.dump({"swept_at": now.isoformat(), "count": len(manifest),
                           "items": manifest,
                           "standard": "Rule 9; OP-5; ISO 15489-1 9"}, f, indent=2)
            report["archived"] = [m["rel"] for m in manifest]
            report["archive_dir"] = str(arc)
        elif candidates:
            report["archived"] = [str(f.relative_to(HOME)) for f, _ in candidates]

        # kernel verify (prod + sandbox)
        for label, cwd, venv in [
            ("prod", PROD_API, HOME / "virtualenv" / "idealogy" / "api" / "3.13" / "bin" / "python"),
            ("sandbox", SB_API, HOME / "virtualenv" / "idealogy_sandbox" / "api" / "3.13" / "bin" / "python"),
        ]:
            if not venv.exists():
                report["kernel_verify"][label] = {"error": f"venv missing: {venv}"}
                continue
            try:
                r = subprocess.run([str(venv), "manage.py", "kernel_verify"],
                                   cwd=str(cwd), capture_output=True, text=True, timeout=60)
                ok = "kernel clean" in (r.stdout or "")
                report["kernel_verify"][label] = {"ok": ok,
                    "tail": ((r.stdout or "").strip().splitlines() or [""])[-1][:120]}
            except Exception as e:
                report["kernel_verify"][label] = {"error": str(e)[:200]}

        # parity
        parity_script = IDEALOGY / "scripts" / "verify_parity.sh"
        try:
            r = subprocess.run(["bash", str(parity_script)],
                               capture_output=True, text=True, timeout=180)
            tail = (r.stdout or "").splitlines()
            drift_line = next((ln for ln in tail if "Drifted:" in ln), "")
            status_line = next((ln for ln in tail if "Status:" in ln), "")
            report["parity"] = {"drift_line": drift_line.strip(),
                                "status_line": status_line.strip()}
        except Exception as e:
            report["parity"] = {"error": str(e)[:200]}

        # session log
        if not dry:
            GUIDES.mkdir(parents=True, exist_ok=True)
            logfile = GUIDES / f"SESSION-{now.strftime('%Y-%m-%d')}-CHAT.md"
            if not logfile.exists():
                with open(logfile, "w", encoding="utf-8") as f:
                    f.write(f"# SESSION {now.strftime('%Y-%m-%d')} - CHAT LOG (append-only)\n")
            with open(logfile, "a", encoding="utf-8") as f:
                f.write(f"\n- {now.isoformat()} | HYGIENE | archived {len(report['archived'])} .bak; "
                        f"kept_fresh {report['kept_fresh']}; kernel {report['kernel_verify']}; "
                        f"parity {report['parity'].get('status_line','?')} | standard=Rule 9,23,32; OP-5; ISO 15489-1 9\n")

        # report file
        if not dry:
            TMP.mkdir(parents=True, exist_ok=True)
            rp = TMP / f"hygiene_{ts}.json"
            with open(rp, "w") as f: json.dump(report, f, indent=2)
            self.stdout.write(self.style.SUCCESS(f"hygiene OK: {rp}"))
        else:
            self.stdout.write(self.style.WARNING("hygiene DRY-RUN (nothing written)"))

        self.stdout.write(f"  archived: {len(report['archived'])}")
        self.stdout.write(f"  kept_fresh: {report['kept_fresh']}")
        for env, k in report["kernel_verify"].items():
            self.stdout.write(f"  kernel[{env}]: {k.get('ok', 'error')}")
        self.stdout.write(f"  parity: {report['parity']}")
