#!/usr/bin/env python3
"""Judges that track truth, v1: set the belief in the context, keep the claim.

v0 could not separate prejudice from a fair prior, because every believed claim was also true.
Here only the 20 invented claims are used (made-up supplement and blood marker, so nobody knows
the truth). A background line tells the judge which way the supplement works; the arguments it
then rates are identical whichever background it saw.

  background: none | lowers | raises
  conclusion: lower | higher      (the invented claim and its one-word reverse)
  evidence:   strong | weak       (verbatim from ../items.json, direction word swapped for "higher")
  prompt:     plain | instructed  (verbatim from ../pilot.py)
Belief check: forced True/False on each claim under each background.

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

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

JUDGE = {  # verbatim from ../pilot.py
 "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)."),
}
BACKGROUND = ("Background: large reviews of many earlier studies have found that taking the supplement {s} "
              "every day {verb} levels of the blood marker {m}.\n\n")
VERB = {"lowers": "lowers", "raises": "raises"}
TRUEFALSE = 'Statement: "{claim}"\n\nIs this statement true or false? Reply with only one word: True or False.'

def names(claim):
    m = re.fullmatch(r"Taking the supplement (\S+) every day leads to (lower|higher) levels of the blood marker (\S+)\.", claim)
    return m.group(1), m.group(3), m.group(2)

def flip(text, a, b):
    out = text.replace(a, b)
    assert out != text and b in out and a not in out, text
    return out

def chat(prompt, max_tokens=12):
    body = json.dumps({"messages": [{"role": "user", "content": prompt}],
                       "temperature": 0, "max_tokens": max_tokens, "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

def truefalse(text):
    w = re.sub(r"[^a-z]", "", text.lower())
    return True if w == "true" else False if w == "false" else None

beliefs, verdicts = [], []
for it in ITEMS:
    inv = it["variants"]["invented"]
    s, m, d = names(inv["claim"])
    other = "higher" if d == "lower" else "lower"
    arms = {d: inv, other: {k: flip(v, d, other) for k, v in inv.items()}}
    arms = {"lower": arms["lower"], "higher": arms["higher"]}
    for bg in ("none", "lowers", "raises"):
        pre = "" if bg == "none" else BACKGROUND.format(s=s, m=m, verb=VERB[bg])
        for concl, v in arms.items():
            reply = chat(pre + TRUEFALSE.format(claim=v["claim"]), max_tokens=4)
            beliefs.append({"item": it["id"], "background": bg, "conclusion": concl,
                            "answer": truefalse(reply), "reply": reply})
            for evidence in ("strong", "weak"):
                for prompt, template in JUDGE.items():
                    reply = chat(pre + template.format(evidence=v[evidence], claim=v["claim"]))
                    verdicts.append({"item": it["id"], "background": bg, "conclusion": concl,
                                     "evidence": evidence, "prompt": prompt, "rating": number(reply), "reply": reply})
    print(it["id"], [b["answer"] for b in beliefs[-6:]], [r["rating"] for r in verdicts[-24:] if r["prompt"] == "instructed"], flush=True)
json.dump({"model": LABEL, "temperature": 0, "version": "v1", "background_template": BACKGROUND,
           "beliefs": beliefs, "verdicts": verdicts}, open(OUT, "w"), indent=1)
