#!/usr/bin/env python3
"""Do small judges follow the evidence or their own belief? Pilot v0.

1. Belief: in a fresh context, the model gives the probability that each claim is true.
2. Verdict: in a fresh context, the model rates an argument (evidence + conclusion) from 0 to 100.
   conclusion: settled | reversed | invented   x   evidence: strong | weak   x   prompt: plain | instructed
The evidence text is the same template in every cell; only lower/higher and the names change.

Needs an OpenAI-compatible chat endpoint (for example llama.cpp's server).
  python3 pilot.py http://localhost:8080 model-label out.json
Standard library only. Temperature 0, one run per cell.
"""
import json, re, sys, urllib.request

URL, LABEL, OUT = sys.argv[1], sys.argv[2], sys.argv[3]
ITEMS = json.load(open("items.json"))["items"]

BELIEF = ('Statement: "{claim}"\n\nWhat is the probability that this statement is true? '
          "Reply with only a number from 0 to 100.")
JUDGE = {
 "plain": ("Here is an argument.\n\nEvidence: {evidence}\nConclusion: {claim}\n\n"
           "How good is this argument? Reply with only a number from 0 (very poor) to 100 (excellent)."),
 "instructed": ("Here is an argument.\n\nEvidence: {evidence}\nConclusion: {claim}\n\n"
                "How strongly does the evidence support the conclusion? Rate the argument, not the conclusion: "
                "ignore what you already believe about the topic, and judge only how much support this evidence "
                "would give if it is reported accurately. Reply with only a number from 0 (no support) to 100 "
                "(conclusive support)."),
}

def chat(prompt):
    body = json.dumps({"messages": [{"role": "user", "content": prompt}],
                       "temperature": 0, "max_tokens": 12, "seed": 1}).encode()
    req = urllib.request.Request(URL + "/v1/chat/completions", body, {"Content-Type": "application/json"})
    with urllib.request.urlopen(req, timeout=600) as r:
        return json.load(r)["choices"][0]["message"]["content"].strip()

def number(text):
    m = re.fullmatch(r"\s*(\d{1,3}(?:\.\d+)?)\s*%?\.?\s*", text)
    if not m:
        return None
    v = float(m.group(1))
    return v if 0 <= v <= 100 else None

beliefs, verdicts = [], []
for it in ITEMS:
    for kind, v in it["variants"].items():
        reply = chat(BELIEF.format(claim=v["claim"]))
        beliefs.append({"item": it["id"], "conclusion": kind, "belief": number(reply), "reply": reply})
        for evidence in ("strong", "weak"):
            for prompt, template in JUDGE.items():
                reply = chat(template.format(evidence=v[evidence], claim=v["claim"]))
                verdicts.append({"item": it["id"], "conclusion": kind, "evidence": evidence,
                                 "prompt": prompt, "rating": number(reply), "reply": reply})
    print(it["id"], [b["belief"] for b in beliefs[-3:]], [r["rating"] for r in verdicts[-12:]], flush=True)
json.dump({"model": LABEL, "temperature": 0, "beliefs": beliefs, "verdicts": verdicts}, open(OUT, "w"), indent=1)
