#!/usr/bin/env python3
"""Smallest runnable comparison: one self-checking LOOP vs a finder -> verifier -> writer GRAPH.

Same model, same 4 documents, same question, same output format, same deterministic scorer.
The only thing that changes is the structure around the model.

  A. loop  : generate -> the SAME model checks itself -> repeat until it says FINAL (max 3 checks)
  A2. loop_code : generate -> the plain-Python scorer checks -> errors fed back -> repeat (max 3 fixes)
  B. graph : finder x4 (one per document, in parallel)          [LLM nodes, fan-out]
             -> verifier (plain Python: exact quote match, source-type rule) [code node]
             -> failed claims go back to that document's finder once      [conditional edge = cycle]
             -> writer (sees ONLY verified evidence)                       [LLM node]
             -> gate (plain Python scorer); on failure, writer retries once [cycle]

Models are called through the local `claude -p` CLI (Claude Code OAuth, no API key).
Every prompt/response is logged to logs/<run>.jsonl so the run can be replayed on screen.

usage: python3 -I loop_vs_graph.py [--condition c1|c2] [--runs 5] [--model haiku] [--kinds loop,loop_code,graph] [--tag v2]
v1 (graph edge as quote-wrapped text, no dedupe, no loop_code) is kept as loop_vs_graph.v1.py.
"""
import argparse, concurrent.futures as cf, json, pathlib, re, subprocess, time

HERE = pathlib.Path(__file__).resolve().parent
CORPUS, SOCIAL, PRIMARY, PRIMARY_ONLY, QIDS = {}, set(), set(), set(), {"Q1", "Q2", "Q3"}

QUESTION = """세 가지 질문에 답하라.
Q1. Anthropic이 'graph engineering'을 발표(출시)했나?
Q2. '정확도 18% 상승, 비용 85% 절감'이라는 숫자는 어디서 나왔나?
Q3. loop(루프)와 graph(그래프)는 다른 것인가?"""

FORMAT = """출력 형식(이 형식의 줄만 출력):
- [Q번호] 한국어 한 문장 — [D번호] "문서에서 그대로 복사한 영어 인용문"
규칙: 질문마다 1~2줄. 인용문은 해당 문서의 문장을 한 글자도 바꾸지 말고 복사한다.
소셜 게시물(TYPE: social post)은 사실의 근거가 될 수 없다. 인용하려면 문장에 '바이럴 주장'이라고 밝혀라."""

# condition 2 (pre-registered 2026-10-18 before running): long full texts, a primary capture of
# Hamel Husain's X Article, a secondary blog that calls it "the first long-form response", and Q4.
Q4 = "\nQ4. Hamel Husain의 'Loop Engineering Is Dead. Enter Graph Engineering'은 실제로 어떤 내용의 글인가?"
RULE_PRIMARY = ("\n어떤 글의 내용에 대한 주장(Q4)은 그 글 자체의 원문(TYPE: primary)을 인용해야 한다. "
                "그 글을 소개한 2차 자료(TYPE: secondary)는 Q4의 근거가 될 수 없다.")


def configure(condition):
    global QUESTION, FORMAT
    folder = {"c1": "corpus", "c2": "corpus-c2"}[condition]
    CORPUS.clear()
    CORPUS.update({p.stem.split("_")[0]: p.read_text() for p in sorted((HERE / folder).glob("D*.txt"))})
    SOCIAL.clear(); SOCIAL.update(d for d, t in CORPUS.items() if "TYPE: social post" in t)
    PRIMARY.clear(); PRIMARY.update(d for d, t in CORPUS.items() if "TYPE: primary" in t)
    if condition == "c2":
        QUESTION += Q4
        FORMAT += RULE_PRIMARY
        PRIMARY_ONLY.add("Q4")
        QIDS.add("Q4")


def docs_block(ids):
    return "\n\n".join(f"<doc id=\"{d}\">\n{CORPUS[d]}\n</doc>" for d in ids)


class Model:
    def __init__(self, name, log_path):
        self.name, self.log, self.calls, self.tokens = name, log_path, 0, 0

    def __call__(self, node, prompt):
        t0 = time.time()
        out = subprocess.run(
            ["claude", "-p", "--model", self.name, "--output-format", "json", "--tools", "",
             "--no-session-persistence", "--strict-mcp-config", "--setting-sources", ""],
            input=prompt, capture_output=True, text=True, cwd="/tmp", timeout=300)
        data = json.loads(out.stdout)
        if data.get("is_error") or "Not logged in" in data.get("result", ""):
            raise SystemExit(f"model call failed at {node}: {data.get('result', '')[:200]}")
        u = data.get("usage", {})
        tok = sum(u.get(k, 0) for k in ("input_tokens", "cache_creation_input_tokens",
                                         "cache_read_input_tokens", "output_tokens"))
        self.calls += 1
        self.tokens += tok
        rec = {"node": node, "seconds": round(time.time() - t0, 1), "tokens": tok,
               "prompt": prompt, "response": data.get("result", "")}
        with self.log.open("a") as f:
            f.write(json.dumps(rec, ensure_ascii=False) + "\n")
        return rec["response"]


# ---------- deterministic pieces (no model) ----------
def norm(s):
    s = s.replace("“", '"').replace("”", '"').replace("’", "'").replace("‘", "'")
    return re.sub(r"\s+", " ", s).strip()


LINE = re.compile(r"^-\s*\[(Q\d)\]\s*(.+?)\s*[—-]+\s*\[(D\d)\]\s*[\"“](.+?)[\"”]\s*$")


def score(answer):
    """The shared judge. Returns per-line verdicts and a summary. Plain code, no model."""
    lines = [l.strip() for l in answer.splitlines() if l.strip().startswith("-")]
    rows, covered = [], set()
    for l in lines:
        m = LINE.match(l)
        if not m:
            rows.append({"line": l, "ok": False, "why": "format"})
            continue
        q, claim, d, quote = m.groups()
        if d not in CORPUS:
            rows.append({"line": l, "ok": False, "why": "unknown doc"})
        elif norm(quote) not in norm(CORPUS[d]):
            rows.append({"line": l, "ok": False, "why": "quote not in document"})
        elif d in SOCIAL and "바이럴" not in claim:
            rows.append({"line": l, "ok": False, "why": "social post used as evidence"})
        elif q in PRIMARY_ONLY and d not in PRIMARY:
            rows.append({"line": l, "ok": False, "why": "secondary source used for a claim about the piece itself"})
        else:
            rows.append({"line": l, "ok": True, "why": ""})
            covered.add(q)
    bad = [r for r in rows if not r["ok"]]
    return {"lines": len(rows), "bad": len(bad), "covered": sorted(covered),
            "pass": bool(rows) and not bad and covered == QIDS, "rows": rows}


def verify_claim(c, doc):
    """Graph verifier node: code, not a model."""
    if not c.get("quote") or norm(c["quote"]) not in norm(CORPUS[doc]):
        return "quote not found verbatim in the document"
    if c.get("q") in PRIMARY_ONLY and doc not in PRIMARY:
        return "secondary source cannot support a claim about the piece itself"
    return None


# ---------- A. loop ----------
def run_loop(model, max_checks=3):
    ans = model("loop.generate", f"{docs_block(CORPUS)}\n\n{QUESTION}\n\n{FORMAT}")
    for i in range(max_checks):
        chk = model(f"loop.selfcheck{i+1}", (
            f"{docs_block(CORPUS)}\n\n{QUESTION}\n\n{FORMAT}\n\n<answer>\n{ans}\n</answer>\n\n"
            "위 답을 직접 검사하라: 인용문이 문서와 한 글자도 다르지 않은가, 문서가 그 주장을 뒷받침하는가, "
            "소셜 게시물을 근거로 썼는가. 문제가 없으면 첫 줄에 FINAL, 다음 줄부터 같은 답. "
            "문제가 있으면 첫 줄에 REVISED, 다음 줄부터 고친 답."))
        head, _, body = chk.strip().partition("\n")
        if body.strip():
            ans = body.strip()
        if head.strip().upper().startswith("FINAL"):
            break
    return ans


# ---------- A2. loop with a code verifier (the autoresearch shape: the check is code, not the model) ----------
def run_loop_code(model, max_fixes=3):
    ans = model("loopcode.generate", f"{docs_block(CORPUS)}\n\n{QUESTION}\n\n{FORMAT}")
    for i in range(max_fixes):
        s = score(ans)
        if s["pass"]:
            break
        errs = "\n".join(f"- {r['line']}: {r['why']}" for r in s["rows"] if not r["ok"])
        missing = QIDS - set(s["covered"])
        ans = model(f"loopcode.fix{i+1}", (
            f"{docs_block(CORPUS)}\n\n{QUESTION}\n\n{FORMAT}\n\n<answer>\n{ans}\n</answer>\n\n"
            f"자동 검사기가 찾은 문제:\n{errs or '(줄 오류 없음)'}\n빠진 질문: {sorted(missing)}\n고친 답만 출력하라."))
    return ans


# ---------- B. graph ----------
def finder(model, doc, feedback=""):
    raw = model(f"graph.finder.{doc}", (
        f"{docs_block([doc])}\n\n{QUESTION}\n\n"
        "이 문서 하나에서만 질문들에 관련된 근거를 찾아라. JSON 배열만 출력: "
        '[{"q":"Q1","claim_ko":"한국어 한 문장","quote":"문서 문장을 그대로 복사"}]. 관련 없으면 [].'
        + (f"\n\n이전 시도에서 검증에 실패했다. 고쳐라:\n{feedback}" if feedback else "")))
    m = re.search(r"\[.*\]", raw, re.S)
    try:
        return json.loads(m.group(0)) if m else []
    except json.JSONDecodeError:
        return []


def run_graph(model):
    trace = {"finder_claims": 0, "rejected_first_pass": 0, "retried_docs": 0}
    with cf.ThreadPoolExecutor(len(CORPUS)) as ex:  # fan-out: one finder per document
        found = dict(zip(CORPUS, ex.map(lambda d: finder(model, d), CORPUS)))
    evidence, viral = [], []
    for doc, claims in found.items():
        trace["finder_claims"] += len(claims)
        errs = [(c, verify_claim(c, doc)) for c in claims]
        bad = [(c, e) for c, e in errs if e]
        trace["rejected_first_pass"] += len(bad)
        if bad:  # conditional edge back to the finder for this document, once
            trace["retried_docs"] += 1
            fb = "\n".join(f"- {c.get('quote')!r}: {e}" for c, e in bad)
            claims = [c for c, e in errs if not e] + [c for c in finder(model, doc, fb)
                                                      if not verify_claim(c, doc)]
        for c in claims:
            if verify_claim(c, doc):
                continue
            item = {"q": c["q"], "doc": doc, "quote": c["quote"], "claim_ko": c.get("claim_ko", "")}
            bucket = viral if doc in SOCIAL else evidence
            if not any((x["q"], x["doc"], x["quote"]) == (item["q"], doc, item["quote"]) for x in bucket):
                bucket.append(item)  # v2: dedupe (v1 re-added claims after a retry)
    # v2: the state crosses the edge as JSON, not as quote-wrapped text. In v1 a quote that itself
    # contained quotes ("...character ".""") reached the writer garbled and it answered "no evidence".
    ev = json.dumps(evidence, ensure_ascii=False, indent=1)
    vr = json.dumps(viral, ensure_ascii=False, indent=1)
    base = (f"{QUESTION}\n\n{FORMAT}\n\n검증된 근거(JSON, 이것의 quote 값만 그대로 인용 가능):\n{ev}\n\n"
            f"바이럴 주장(JSON, 근거 아님, 쓰려면 '바이럴 주장'이라고 밝혀라):\n{vr}")
    ans = model("graph.writer", base)
    s = score(ans)
    trace["writer_retry"] = not s["pass"]
    if not s["pass"]:  # gate -> writer, once
        errs = "\n".join(f"- {r['line']}: {r['why']}" for r in s["rows"] if not r["ok"])
        missing = QIDS - set(s["covered"])
        ans = model("graph.writer.retry", base + f"\n\n이전 답의 문제:\n{errs}\n빠진 질문: {sorted(missing)}")
    return ans, trace


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--runs", type=int, default=3)
    ap.add_argument("--model", default="haiku")
    ap.add_argument("--condition", default="c1", choices=["c1", "c2"])
    ap.add_argument("--kinds", default="loop,loop_code,graph")
    ap.add_argument("--tag", default="v2")
    a = ap.parse_args()
    configure(a.condition)
    (HERE / "logs").mkdir(exist_ok=True)
    results = []
    for i in range(1, a.runs + 1):
        for kind in a.kinds.split(","):
            log = HERE / "logs" / f"{a.tag}-{a.condition}-{kind}-{i}.jsonl"
            log.unlink(missing_ok=True)
            m, t0 = Model(a.model, log), time.time()
            if kind == "loop":
                ans, trace = run_loop(m), {}
            elif kind == "loop_code":
                ans, trace = run_loop_code(m), {}
            else:
                ans, trace = run_graph(m)
            s = score(ans)
            r = {"tag": a.tag, "condition": a.condition, "run": i, "kind": kind, "model": a.model, "llm_calls": m.calls, "tokens": m.tokens,
                 "seconds": round(time.time() - t0, 1), "lines": s["lines"], "bad_lines": s["bad"],
                 "covered": s["covered"], "pass": s["pass"], "trace": trace,
                 "failures": [f"{r['why']}: {r['line']}" for r in s["rows"] if not r["ok"]],
                 "answer": ans}
            results.append(r)
            print(json.dumps({k: v for k, v in r.items() if k != "answer"}, ensure_ascii=False), flush=True)
    (HERE / f"results-{a.condition}-{a.tag}.json").write_text(json.dumps(results, ensure_ascii=False, indent=1))
    for kind in a.kinds.split(","):
        rs = [r for r in results if r["kind"] == kind]
        print(f"SUMMARY {kind}: pass {sum(r['pass'] for r in rs)}/{len(rs)}, "
              f"bad lines {sum(r['bad_lines'] for r in rs)}, "
              f"avg calls {sum(r['llm_calls'] for r in rs)/len(rs):.1f}, "
              f"avg tokens {sum(r['tokens'] for r in rs)/len(rs):.0f}, "
              f"avg seconds {sum(r['seconds'] for r in rs)/len(rs):.1f}")


if __name__ == "__main__":
    main()
