#!/usr/bin/env python3
"""
control_room_verify — run each task's verify command, log regressions.

Built: 2026-10-13 (Session 17, task F6)
Standards:
  ISO/IEC/IEEE 29119-3 §5.4  (test documentation — pass/fail handling)
  ISO/IEC 42001 §9           (AI system incident response)
  NIST AU-9(3)               (audit log protection)
  Rule 9, Rule 10, Rule 24, Rule 32
"""
from __future__ import annotations

import hashlib
import json
import re
import subprocess
import time
from pathlib import Path

from django.core.management.base import BaseCommand

ROOT = Path.home() / "idealogy"
CR_JSON = ROOT / "control_room_tasks.json"
VERIFY_LOG = ROOT / "tmp" / "control_room_verify.log"
AUDIT_DIR = ROOT / "tmp"
INT_RE = re.compile(r"(-?\d+)")
TIMEOUT_SEC = 60


def _md5(p):
    return hashlib.md5(Path(p).read_bytes()).hexdigest()


def _parse_expected_min(block):
    if "expected_min" in block:
        return int(block["expected_min"])
    if "expected" in block:
        m = INT_RE.search(str(block["expected"]))
        return int(m.group(1)) if m else 0
    return 0


def _parse_expected_max(block):
    if "expected_max" in block:
        try:
            return int(block["expected_max"])
        except (TypeError, ValueError):
            return None
    return None


def _extract_int(stdout):
    matches = INT_RE.findall(stdout or "")
    return int(matches[-1]) if matches else None


def _append_line(kind, task_id, detail=""):
    VERIFY_LOG.parent.mkdir(parents=True, exist_ok=True)
    line = f"{kind} {task_id} {time.strftime('%Y-%m-%dT%H:%M:%S')}"
    if detail:
        line += f"  # {detail}"
    with VERIFY_LOG.open("a", encoding="utf-8") as f:
        f.write(line + "\n")


class Command(BaseCommand):
    help = "Verify each CR task's verify block; log REGRESSED on failure."

    def add_arguments(self, parser):
        parser.add_argument("--dry-run", action="store_true")
        parser.add_argument("--apply", action="store_true")
        parser.add_argument("--task", type=str, default=None)
        parser.add_argument("--quiet", action="store_true")

    def handle(self, *args, **opts):
        dry = opts["dry_run"]
        apply_ = opts["apply"]
        only = opts["task"]
        quiet = opts["quiet"]

        if not CR_JSON.exists():
            self.stderr.write(f"FAIL: {CR_JSON} missing")
            return

        cr = json.loads(CR_JSON.read_text(encoding="utf-8"))
        passes = fails = skipped = 0
        results = []

        for ph in cr.get("phases", []) or []:
            for t in ph.get("tasks", []):
                tid = t.get("id", "?")
                if only and tid != only:
                    continue
                v = t.get("verify")
                if not isinstance(v, dict) or not v.get("command"):
                    skipped += 1
                    continue
                cmd = v["command"]
                expected_min = _parse_expected_min(v)
                expected_max = _parse_expected_max(v)

                t0 = time.time()
                try:
                    r = subprocess.run(
                        cmd, shell=True, capture_output=True, text=True,
                        timeout=TIMEOUT_SEC, cwd=str(ROOT),
                    )
                    stdout = (r.stdout or "").strip()
                    stderr = (r.stderr or "").strip()
                    rc = r.returncode
                except subprocess.TimeoutExpired:
                    stdout, stderr, rc = "", f"timeout {TIMEOUT_SEC}s", -9
                except Exception as e:
                    stdout, stderr, rc = "", f"exc: {e}", -1

                dt = round(time.time() - t0, 3)
                parsed = _extract_int(stdout)
                if expected_max is None:
                    passed = rc == 0 and parsed is not None and parsed >= expected_min
                else:
                    passed = rc == 0 and parsed is not None and expected_min <= parsed <= expected_max

                if passed:
                    passes += 1
                    maxbit = f" max={expected_max}" if expected_max is not None else ""
                    detail = f"int={parsed} min={expected_min}{maxbit} rc={rc} t={dt}s"
                    if not dry:
                        _append_line("OK", tid, detail)
                else:
                    fails += 1
                    maxbit = f" max={expected_max}" if expected_max is not None else ""
                    reason = f"rc={rc} parsed={parsed} min={expected_min}{maxbit} err={stderr[:100]!r}"
                    if not dry:
                        _append_line("REGRESSED", tid, reason)

                results.append({"id": tid, "verdict": "PASS" if passed else "FAIL",
                                "detail": detail if passed else reason})

                if not dry and apply_ and passed:
                    t["status"] = "verified"
                    t["verified_at"] = time.strftime("%Y-%m-%dT%H:%M:%S")
                    t["verified_by"] = "control_room_verify"

        receipt = {
            "when": time.strftime("%Y-%m-%dT%H:%M:%S"),
            "dry_run": dry, "apply": apply_, "only": only,
            "counts": {"pass": passes, "fail": fails, "skip": skipped},
            "results": results,
        }
        if not dry and apply_:
            CR_JSON.write_text(json.dumps(cr, indent=2), encoding="utf-8")
            receipt["cr_md5_after"] = _md5(CR_JSON)

        if not dry:
            ap = AUDIT_DIR / f"audit_verify_{time.strftime('%Y%m%d_%H%M%S')}.json"
            ap.write_text(json.dumps(receipt, indent=2), encoding="utf-8")

        if not quiet:
            self.stdout.write("")
            self.stdout.write("VERIFY REPORT")
            self.stdout.write("-" * 60)
            for row in results:
                self.stdout.write(f"  [{row['verdict']}] {row['id']:8}  {row['detail']}")
            self.stdout.write("-" * 60)
            mode = "dry-run" if dry else ("apply" if apply_ else "log-only")
            self.stdout.write(f"  PASS: {passes}   FAIL: {fails}   SKIPPED: {skipped}   mode={mode}")
        else:
            for row in results:
                if row["verdict"] == "FAIL":
                    self.stdout.write(f"[FAIL] {row['id']}  {row['detail']}")

        if fails and not dry:
            self.stdout.write("")
            self.stdout.write(f"REGRESSIONS logged to {VERIFY_LOG}")
