"""Two boots of one build, compared one at a time (the cards hold one TP2 engine): the admin console's
decode-path scorer (arbi_serve.admin_console.decode_fidelity) split into a capture per boot and a fold.
  ref URL MODEL OUT.pkl [prompts repeats depth]   boot 1: build the cells, generate the reference continuation, force it twice
  cap URL MODEL REF.pkl OUT.pkl                    any boot: force boot 1's continuation once more
  cmp REF.pkl A.pkl B.pkl [OUT.json]               exact equality of the two captures' logprob rows, and the scorer's fold
A capture named "ref" in cmp means boot 1's own first forced capture."""
import asyncio, json, pickle, sys
from types import SimpleNamespace
from arbi_serve.admin_console import decode_fidelity as df
from arbi_serve.admin_console import decode_fidelity_prompts as dp
from arbi_serve.admin_console import targets
from arbi_serve.admin_console.ab_probe import CANONICAL_SEED, canonical_prompt
from arbi_serve.admin_console.sweep import AB_PROMPT_SHAPE, frame
SAMPLER = {"temperature": 1.0, "top_p": 0.95, "top_k": 20}
BANDS = [1]
def emit(_f): print(".", end="", flush=True)
async def ref(url, model, out, n_prompts=8, repeats=2, depth=1024):
    A = SimpleNamespace(base_url=url, token=None, model=model)
    async def count(text): return await targets._count_prompt_tokens(A.base_url, None, A.model, text)
    first = await canonical_prompt(count, 0, seed=CANONICAL_SEED, target_tokens=depth, kind_idx=AB_PROMPT_SHAPE[0], lead_override=AB_PROMPT_SHAPE[1])
    spec = dp.parse_score_cells(n_prompts, repeats, "chat")
    cells, manifest = await dp.score_cells(A, {(depth, 1): [first]}, spec, seed=CANONICAL_SEED, shape=AB_PROMPT_SHAPE)
    by_cell = df.cell_prompts(cells)
    r = await df.capture_reference(A, by_cell, BANDS, SAMPLER, emit, frame)
    pickle.dump({"by_cell": by_cell, "ref": r, "manifest": manifest, "spec": spec, "depth": depth}, open(out, "wb"))
    errs = [c["reference"]["error"] for c in r["cells"].values() if c["reference"]["error"]]
    print("\ncells", len(r["cells"]), "errors", errs[:3])
async def cap(url, model, refp, out):
    B = SimpleNamespace(base_url=url, token=None, model=model)
    d = pickle.load(open(refp, "rb"))
    arm = await df.capture_arm(B, d["by_cell"], d["ref"], BANDS, SAMPLER, emit, frame)
    pickle.dump(arm, open(out, "wb"))
    print("\ncells", len(arm["cells"]))
def rows_of(d, name, path):
    if name == "ref":
        return {c: v["bands"][1]["first"] for c, v in d["ref"]["cells"].items() if v["bands"]}
    return {c: v["bands"][1] for c, v in pickle.load(open(path, "rb"))["cells"].items() if v["bands"]}
def cmp(refp, a, b, out=None):
    d = pickle.load(open(refp, "rb"))
    ra, rb = rows_of(d, a, a), rows_of(d, b, b)
    pos = same = 0; maxd = 0.0; first_diff = {}
    for c in ra:
        for x, y in zip(ra[c], rb[c]):
            if x.get("error") or y.get("error"):
                print("ERROR", c, x.get("error"), y.get("error")); continue
            for i, (p, q) in enumerate(zip(x["rows"], y["rows"])):
                pos += 1
                if json.dumps(p, sort_keys=True, default=str) == json.dumps(q, sort_keys=True, default=str): same += 1
                else:
                    first_diff.setdefault(str(c), i)
                    try:
                        pm, qm = dict(p), dict(q)
                        maxd = max([maxd] + [abs(float(pm[k]) - float(qm[k])) for k in pm if k in qm])
                    except Exception: pass
    pseudo = {"cells": {c: {"reference": d["ref"]["cells"][c]["reference"], "bands": {1: {"first": ra[c], "second": ra[c]}}} for c in ra}}
    arm = {"cells": {c: {"bands": {1: rb[c]}} for c in rb}}
    fold = df.fold_decode(pseudo, arm, BANDS, sampler=SAMPLER)
    band = (fold.get("row_bands") or [{}])[0]
    keep = {k: v for k, v in band.items() if k not in ("cells", "null_control")}
    res = {"a": a, "b": b, "positions": pos, "identical_positions": same, "max_abs_logprob_diff": maxd,
           "first_differing_position_by_cell": first_diff, "fold": keep}
    print(json.dumps(res, default=str)[:3500])
    if out: open(out, "a").write(json.dumps(res, default=str) + "\n")
m = sys.argv[1]
if m == "ref": asyncio.run(ref(sys.argv[2], sys.argv[3], sys.argv[4], *(int(v) for v in sys.argv[5:8])))
elif m == "cap": asyncio.run(cap(*sys.argv[2:6]))
else: cmp(*sys.argv[2:])
