"""Detached gated build: run the full CLI build and record the verdict.

Spawned by revise.py's fast path so customers see previews in seconds while
STEP/STL/gates grind in the background. Verdict lands in jobs.json under
"concept-<name>" (triage lists failures; a failure also reopens a note on the
design so it surfaces on the studio page).
"""

from __future__ import annotations

import json
import subprocess
import sys
import uuid
from datetime import datetime, timezone
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
PYBIN = str(ROOT / ".cad-venv" / "bin" / "python")
JOBS = ROOT / "artifacts" / "review" / "jobs.json"
COMMENTS = ROOT / "artifacts" / "review" / "comments.json"


def main() -> int:
    name, spec_json = sys.argv[1], sys.argv[2]
    r = subprocess.run([PYBIN, "-m", "ringcli.cli", "build", "--spec-json",
                        spec_json], cwd=ROOT, capture_output=True, text=True,
                       timeout=1800)
    out = r.stdout.strip()
    try:
        result = json.loads(out[out.index("{"):])
    except Exception:
        result = {"ok": False, "errors": [(out or r.stderr)[-300:]]}
    jobs = json.loads(JOBS.read_text()) if JOBS.exists() else {}
    jobs[f"concept-{name}"] = {
        "status": "done" if result.get("ok") else "failed", "result": result,
        "finished": datetime.now(timezone.utc).isoformat(timespec="seconds")}
    jobs[f"revision-{name}"] = {
        "status": "verified" if result.get("ok") else "failed",
        "updated": datetime.now(timezone.utc).isoformat(timespec="seconds")}
    JOBS.parent.mkdir(parents=True, exist_ok=True)
    JOBS.write_text(json.dumps(jobs, indent=2))
    if not result.get("ok"):
        data = json.loads(COMMENTS.read_text()) if COMMENTS.exists() else {"comments": []}
        data["comments"].append({
            "id": uuid.uuid4().hex[:8], "design": name, "kind": "system",
            "text": "revision preview shown, but the full build FAILED its "
                    "gates: " + "; ".join(result.get("errors", [])),
            "status": "open",
            "created": datetime.now(timezone.utc).isoformat(timespec="seconds")})
        COMMENTS.write_text(json.dumps(data, indent=2))
    return 0


if __name__ == "__main__":
    sys.exit(main())
