"""control_room_done - mark a Control Room task as done.

Turn 21 (2026-10-11). Single canonical writer for the Control Room JSON.

Usage:
    python manage.py control_room_done <task_id>
        [--artifact "path/to/file"] [--note "short note"]

Behavior:
    1. Loads control_room_tasks.json from THIS environment
    2. Finds task by id; refuses if already done
    3. Sets status=done, completed_at, artifact, note
    4. Recomputes metadata.total and writes back
    5. Mirrors the same file to the OTHER environment
    6. Writes an audit JSON to tmp/
    7. Prints the new percentage

Standards: Rule 9 (append-only audit); Rule 10 (one writer); Rule 23
(one job); Rule 24 (md5-pinned cross-env); Rule 28; ISO 9001 7.5.3;
Kleppmann DDIA Ch. 7 (atomic write).
"""
import hashlib
import json
import shutil
from datetime import datetime, timezone
from pathlib import Path

from django.core.management.base import BaseCommand, CommandError


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


class Command(BaseCommand):
    help = "Mark a Control Room task as done and mirror both envs."

    def add_arguments(self, parser):
        parser.add_argument("task_id", type=str)
        parser.add_argument("--artifact", type=str, default="")
        parser.add_argument("--note", type=str, default="")

    def handle(self, *args, **opts):
        this_home = Path.home()
        prod_home = this_home / "idealogy"
        sand_home = this_home / "idealogy_sandbox"

        cr_prod = prod_home / "control_room_tasks.json"
        cr_sand = sand_home / "control_room_tasks.json"

        if not cr_prod.exists() or not cr_sand.exists():
            raise CommandError("control_room_tasks.json missing on one env")

        data = json.loads(cr_prod.read_text())

        tid = str(opts["task_id"])
        found = None
        for ph in data["phases"]:
            for t in ph.get("tasks", []):
                if str(t.get("id")) == tid:
                    found = t
                    break
            if found:
                break

        if not found:
            raise CommandError("task id not found: " + tid)
        if found.get("status") == "done":
            self.stdout.write("task " + tid + " already done; no change")
            return

        found["status"] = "done"
        found["completed_at"] = datetime.now(timezone.utc).isoformat()
        if opts["artifact"]:
            found["artifact"] = opts["artifact"]
        if opts["note"]:
            found["note"] = opts["note"]

        data["metadata"]["last_updated"] = datetime.now(timezone.utc).isoformat()
        data["metadata"]["total"] = sum(
            len(p.get("tasks", [])) for p in data["phases"]
        )

        out = json.dumps(data, indent=2, ensure_ascii=False)
        cr_prod.write_text(out)
        cr_sand.write_text(out)

        pm = _md5(cr_prod)
        sm = _md5(cr_sand)

        done = sum(
            1 for p in data["phases"] for t in p.get("tasks", [])
            if t.get("status") == "done"
        )
        total = data["metadata"]["total"]
        pct = int(round(done / total * 100)) if total else 0

        audit = prod_home / "tmp" / (
            "audit_cr_done_" + tid + "_"
            + datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S") + ".json"
        )
        audit.parent.mkdir(parents=True, exist_ok=True)
        audit.write_text(json.dumps({
            "event": "control_room_mark_done",
            "task_id": tid,
            "artifact": opts["artifact"],
            "note": opts["note"],
            "ts": datetime.now(timezone.utc).isoformat(),
            "done": done,
            "total": total,
            "pct": pct,
            "prod_md5": pm,
            "sand_md5": sm,
            "parity": "OK" if pm == sm else "DRIFT",
        }, indent=2))

        self.stdout.write(
            "marked " + tid + " done  |  "
            + str(done) + "/" + str(total) + "  " + str(pct) + "%"
            + "  parity=" + ("OK" if pm == sm else "DRIFT")
        )
        self.stdout.write("audit: " + audit.name)
