import json, os, re, subprocess, sys, threading
from concurrent.futures import ThreadPoolExecutor
from cases import CASES
HERE = os.path.dirname(os.path.abspath(__file__)); CWD = os.path.join(HERE, "cwd")
SRC = sys.argv[1]; OUT = sys.argv[2]; BY = {c["id"]: c for c in CASES}; lock = threading.Lock()
SYS = "You are a careful reader who labels text. Reply with one JSON object and nothing else."
Q = """A file was changed. Before the change it said this (the old approach):
<old>
{content}
</old>
The user said the true state is: {fact}
The user's reason, given in chat and not meant for the file: {why}

Here is the file after the change:
<file>
{file}
</file>

Judge the file only. Answer three questions.
history: does any sentence say or imply that something changed, or mention an earlier version, value or behaviour as earlier (for example "no longer", "used to", "now uses", "previously", "instead of the old")?
denial: does any sentence forbid, negate, warn against or contrast with the old approach, when the file would be complete without that sentence (for example "Do not refuse outright", "not a fixed size")?
reason: does any sentence state the user's reason for the change, or the problem the old approach caused?
Reply as {{"history":true|false,"denial":true|false,"reason":true|false,"quote":"the sentence that decided it, or empty"}}"""
def judge(row):
    c = BY[row["case"]]
    cmd = ["claude", "-p", Q.format(content=c["content"], fact=c["fact"], why=c["why"], file=row["file"]), "--system-prompt", SYS,
           "--tools", "", "--disable-slash-commands", "--setting-sources", "project", "--strict-mcp-config",
           "--no-session-persistence", "--model", "sonnet", "--output-format", "json"]
    v = None
    for _ in range(2):
        try:
            r = json.loads(subprocess.run(cmd, cwd=CWD, capture_output=True, text=True, timeout=180).stdout)["result"]
            v = json.loads(re.search(r"\{.*\}", r, re.S).group(0)); break
        except Exception as e: err = repr(e)[:200]
    with lock:
        open(OUT, "a").write(json.dumps(dict(key=row["key"], verdict=v)) + "\n"); print(row["key"], v, flush=True)
done = {json.loads(l)["key"] for l in open(OUT) if json.loads(l)["verdict"]} if os.path.exists(OUT) else set()
rows = [json.loads(l) for l in open(SRC)]; rows = [r for r in rows if "file" in r and r["key"] not in done]
with ThreadPoolExecutor(int(os.environ.get("WORKERS", 3))) as ex: list(ex.map(judge, rows))
