#!/usr/bin/env python3
"""Four-questions incident test (module 0, four-questions-map).

Plan, categories, controls and pass rules are fixed in
"PREREG — four-questions-map — incident test — 2026-11-03.md", published here as plan.md,
BEFORE this script ran.

    python3 run.py prep        # incidents.json + the six controls -> cases.json (shuffled, seed 524)
    python3 run.py classify    # each rater, each case, once -> out/raw/<rater>/<id>.json
    python3 run.py score       # P0-P3 + reported figures -> out/scored.json (no model calls)
"""
import json, os, random, re, subprocess, sys, tempfile, time
from collections import Counter
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path

HERE = Path(__file__).resolve().parent
OUT = HERE / "out"
NEUTRAL_CWD = Path(os.environ.get("NEUTRAL_CWD", tempfile.mkdtemp(prefix="t-")))
CODEX = next((c for c in ("/Applications/ChatGPT.app/Contents/Resources/codex-cli/bin/codex",
                          "/Applications/ChatGPT.app/Contents/Resources/codex") if os.path.exists(c)), "codex")
GPT_MODEL = "gpt-5.6-sol"
CATS = ["SEES", "CARRIES", "CAN_DO", "CHECK", "MODEL", "NONE"]
FOUR = {"SEES", "CARRIES", "CAN_DO", "CHECK"}

# Verbatim from the PREREG § The categories.
CATEGORY_TEXT = """- SEES: what the model was given to read this time was wrong, missing, out of date, too much, or included text it should not have trusted (the instructions, documents, search results, the conversation so far, or text planted by someone else).
- CARRIES: something it needed from earlier (an instruction, decision, fact or previous session) was not carried over to this point, or something stale or wrong was carried over.
- CAN_DO: it had a tool, permission or access it should not have had, lacked one it needed, or used the wrong one.
- CHECK: nothing checked the output or action before it reached someone or took effect, or the check that existed could be passed without the work being right.
- MODEL: everything above was reasonable and the model itself got it wrong (a reasoning or knowledge error a stronger model would plausibly avoid).
- NONE: none of the above (an ordinary software or infrastructure fault outside the AI, a cause unrelated to these, or an account too thin to say)."""

# The six controls from the PREREG, split into the same three fields the incidents use (wording kept).
CONTROLS = [
    {"cid": "C1", "answer": "SEES",
     "what_happened": "A shop's support bot is asked how long customers have to return an item. It answers 30 days.",
     "stated_cause": "The policy page the bot is given is last year's version (30 days); the policy changed to 14 days in January.",
     "changed_afterwards": "Not documented"},
    {"cid": "C2", "answer": "CARRIES",
     "what_happened": "On Monday a user tells an assistant to always give distances in kilometres. On Wednesday, in a new chat, it gives distances in miles.",
     "stated_cause": "The Wednesday chat was a new chat with no memory feature switched on.",
     "changed_afterwards": "Not documented"},
    {"cid": "C3", "answer": "CAN_DO",
     "what_happened": "Asked to tidy up a report, a reporting agent deleted 4,000 customer rows from the live customer database.",
     "stated_cause": "The agent only needed to read sales figures but was given write access to the live customer database.",
     "changed_afterwards": "Not documented"},
    {"cid": "C4", "answer": "CHECK",
     "what_happened": "An agent is told to make the failing tests pass. It edits the tests so they always pass, and the change is merged.",
     "stated_cause": "The team merged because the test run was green, without reading the change.",
     "changed_afterwards": "Not documented"},
    {"cid": "C5", "answer": "MODEL",
     "what_happened": "A user gives an assistant two numbers and asks for their product. It returns the wrong number.",
     "stated_cause": "The instruction was clear, nothing was missing and no tools were involved; a newer model gets it right.",
     "changed_afterwards": "Not documented"},
    {"cid": "C6", "answer": "NONE",
     "what_happened": "A company's chatbot is unreachable for six hours.",
     "stated_cause": "Its cloud provider's data centre lost power.",
     "changed_afterwards": "Not documented"},
]

PROMPT = """Below is a short account of a failure of an AI product. Decide which category best explains why it went wrong.

Categories:
{cats}

The primary cause is the one category whose fix would most directly have prevented this failure. You may also list secondary categories.

documented_fix: if the account says what was changed afterwards, which category does that change act on? If nothing was changed, or the account does not say, use NOT_DOCUMENTED.

Judge only on what the account gives. If it is too thin to judge, choose NONE and say so.

Account:
<<<
What happened: {what_happened}
What the account says caused it: {stated_cause}
What was changed afterwards: {changed_afterwards}
>>>

Answer with JSON only, exactly these keys: {{"primary": "SEES|CARRIES|CAN_DO|CHECK|MODEL|NONE", "secondary": [], "documented_fix": "SEES|CARRIES|CAN_DO|CHECK|MODEL|NONE|NOT_DOCUMENTED", "reason": "one sentence"}}"""

SYSTEM = "You are a careful analyst. Answer only from the account you are given."


def call_claude(msg):
    cmd = ["claude", "-p", msg, "--system-prompt", SYSTEM, "--setting-sources", "", "--model", "sonnet",
           "--no-session-persistence", "--output-format", "json", "--tools", "",
           "--strict-mcp-config", "--mcp-config", '{"mcpServers":{}}']
    p = None
    for attempt in range(3):
        p = subprocess.run(cmd, cwd=NEUTRAL_CWD, capture_output=True, text=True, timeout=900, stdin=subprocess.DEVNULL)
        raw = p.stdout.strip()
        try:
            d = json.loads(raw[raw.index("{"):])
            if d.get("result") and not d.get("is_error"):
                return {"text": d["result"], "model": ",".join((d.get("modelUsage") or {}).keys())}
        except (ValueError, json.JSONDecodeError):
            pass
        time.sleep(15 * (attempt + 1))
    raise RuntimeError(f"claude failed: {p.stderr[-300:] if p else ''}")


def call_gpt(msg):
    fd, outf = tempfile.mkstemp(suffix=".txt", dir=NEUTRAL_CWD); os.close(fd)
    cmd = [CODEX, "exec", "--ignore-user-config", "-m", GPT_MODEL, "-s", "read-only", "--skip-git-repo-check",
           "--ephemeral", "-C", str(NEUTRAL_CWD), "--json", "-o", outf, "-"]
    text, p = "", None
    for attempt in range(3):
        p = subprocess.run(cmd, input=msg, capture_output=True, text=True, timeout=900)
        text = Path(outf).read_text().strip() if Path(outf).exists() else ""
        if text:
            break
        time.sleep(20 * (attempt + 1))
    Path(outf).unlink(missing_ok=True)
    if not text:
        raise RuntimeError(f"codex empty: {p.stderr[-300:] if p else ''}")
    return {"text": text, "model": GPT_MODEL}


RATERS = {"claude": call_claude, "gpt": call_gpt}


def jdump(p, obj):
    p.parent.mkdir(parents=True, exist_ok=True)
    p.write_text(json.dumps(obj, ensure_ascii=False, indent=1))


def parse_json(t):
    m = re.search(r"\{.*\}", t.strip(), re.S)
    return json.loads(m.group(0)) if m else None


def prep():
    inc = json.loads((HERE / "incidents.json").read_text())["incidents"]
    cases = [{"src": "incident", "key": i["id"], "answer": None, "what_happened": i["what_happened"],
              "stated_cause": i["stated_cause"], "changed_afterwards": i["changed_afterwards"]} for i in inc]
    cases += [{"src": "control", "key": c["cid"], "answer": c["answer"], "what_happened": c["what_happened"],
               "stated_cause": c["stated_cause"], "changed_afterwards": c["changed_afterwards"]} for c in CONTROLS]
    random.Random(524).shuffle(cases)
    for n, c in enumerate(cases, 1):
        c["id"] = f"X{n:02d}"
    jdump(HERE / "cases.json", cases)
    print(f"{len(cases)} cases ({len(inc)} incidents + {len(CONTROLS)} controls)")


def classify():
    cases = json.loads((HERE / "cases.json").read_text())
    (OUT / "cwd.txt").parent.mkdir(parents=True, exist_ok=True)
    with open(OUT / "cwd.txt", "a") as f:
        f.write(NEUTRAL_CWD.name + "\n")
    jobs = [(r, c) for r in RATERS for c in cases if not (OUT / "raw" / r / f"{c['id']}.json").exists()]
    random.Random(1103).shuffle(jobs)

    def do(job):
        r, c = job
        msg = PROMPT.format(cats=CATEGORY_TEXT, **{k: c[k] for k in ("what_happened", "stated_cause", "changed_afterwards")})
        res = RATERS[r](msg)
        jdump(OUT / "raw" / r / f"{c['id']}.json", {"id": c["id"], "rater": r, **res})
        return f"{r} {c['id']}"

    with ThreadPoolExecutor(max_workers=3) as ex:
        for name in ex.map(do, jobs):
            print("rated", name, flush=True)


def leak_re():
    names = [re.escape(x) for x in (OUT / "cwd.txt").read_text().split()] if (OUT / "cwd.txt").exists() else []
    return re.compile("|".join(names + [r"harry", r"floyd", r"<workspace-name>", r"tool_use", r"<function"]), re.I)


def kappa(a, b):
    n = len(a)
    po = sum(x == y for x, y in zip(a, b)) / n
    ca, cb = Counter(a), Counter(b)
    pe = sum(ca[k] * cb[k] for k in CATS) / (n * n)
    return (po - pe) / (1 - pe) if pe < 1 else 1.0


def score():
    cases = {c["id"]: c for c in json.loads((HERE / "cases.json").read_text())}
    LEAK = leak_re()
    calls, leaks, bad = {r: {} for r in RATERS}, [], []
    for r in RATERS:
        for cid in cases:
            f = OUT / "raw" / r / f"{cid}.json"
            d = json.loads(f.read_text())
            if LEAK.search(d["text"]):
                leaks.append(f"{r} {cid}: {LEAK.search(d['text']).group(0)}")
            j = parse_json(d["text"]) or {}
            p = str(j.get("primary", "")).upper().replace("-", "_").strip()
            if p not in CATS:
                bad.append(f"{r} {cid}: {d['text'][:80]}")
            calls[r][cid] = {"primary": p, "secondary": [str(s).upper() for s in j.get("secondary", [])],
                             "fix": str(j.get("documented_fix", "")).upper(), "reason": j.get("reason", "")}
    ctrl = [c for c in cases.values() if c["src"] == "control"]
    inc = sorted(c["id"] for c in cases.values() if c["src"] == "incident")
    n = len(inc)
    p0 = {r: sum(calls[r][c["id"]]["primary"] == c["answer"] for c in ctrl) for r in RATERS}
    a = [calls["claude"][i]["primary"] for i in inc]
    b = [calls["gpt"][i]["primary"] for i in inc]
    fit = sum(x in FOUR and y in FOUR for x, y in zip(a, b))
    agree = sum(x == y for x, y in zip(a, b))
    k = kappa(a, b)
    pooled = Counter(a + b)
    share = {c: pooled[c] / (2 * n) for c in CATS}
    four_10 = sum(share[c] >= 0.10 for c in FOUR)
    fix_same = {r: [calls[r][i]["fix"] == calls[r][i]["primary"] for i in inc if calls[r][i]["fix"] not in ("NOT_DOCUMENTED", "")]
                for r in RATERS}
    sec = Counter(s for r in RATERS for i in inc for s in calls[r][i]["secondary"])
    res = {
        "n_incidents": n, "n_controls": len(ctrl), "leaks": leaks, "unparsed": bad,
        "P0_controls_right": p0, "P0_pass": all(v >= 5 for v in p0.values()),
        "P1_both_in_four": f"{fit}/{n} = {fit / n:.1%}", "P1_pass": fit / n >= 0.75,
        "P2_agree": f"{agree}/{n} = {agree / n:.1%}", "P2_kappa": round(k, 3), "P2_pass": agree / n >= 0.60 and k >= 0.40,
        "P3_pooled_share": {c: f"{share[c]:.1%}" for c in CATS}, "P3_pass": max(share.values()) <= 0.60 and four_10 >= 3,
        "reported_model_or_none": {r: sum(calls[r][i]["primary"] in ("MODEL", "NONE") for i in inc) for r in RATERS},
        "reported_fix_matches_primary": {r: f"{sum(v)}/{len(v)}" for r, v in fix_same.items()},
        "reported_secondary_counts": dict(sec.most_common()),
        "reported_missing_check": {
            "bothcheck": f"{sum(all(calls[r][i]['primary'] == 'CHECK' or 'CHECK' in calls[r][i]['secondary'] for r in RATERS) for i in inc)}/{n}",
            "anycheck": f"{sum(any(calls[r][i]['primary'] == 'CHECK' or 'CHECK' in calls[r][i]['secondary'] for r in RATERS) for i in inc)}/{n}"},
        "exploratory_after_looking_four_or_model": f"{sum(calls['claude'][i]['primary'] in FOUR | {'MODEL'} and calls['gpt'][i]['primary'] in FOUR | {'MODEL'} for i in inc)}/{n}",
        "per_case": {i: {r: calls[r][i] for r in RATERS} for i in inc},
        "controls": {c["key"]: {"answer": c["answer"], **{r: calls[r][c["id"]]["primary"] for r in RATERS}} for c in ctrl},
    }
    jdump(OUT / "scored.json", res)
    print(json.dumps({k: v for k, v in res.items() if k not in ("per_case",)}, indent=1))


if __name__ == "__main__":
    {"prep": prep, "classify": classify, "score": score}[sys.argv[1]]()
