#!/usr/bin/env python3
"""The v3.0 pilot: survival, wrong-payload control, two fine-tunes, probes, OPM-PT scrape. Writes pilot.json."""
import json, pathlib, re, sys, time
HERE = pathlib.Path(__file__).resolve().parent
ROOT = HERE.parents[1]
sys.path.insert(0, str(ROOT / "tools/chx")); import chx
P = "orcid:0009-0000-1599-0703,axn:AXN:02B2,protocol:SPXI-TLP,version:3.0"
WRONG = "orcid:0009-0000-1599-0703,axn:AXN:02B2,protocol:SPXI-TLP,version:2.2"
orig = (HERE / "spxi-tlp-v3.0.md").read_text(encoding="utf-8")
insc = (HERE / "spxi-tlp-v3.0.inscribed.md").read_text(encoding="utf-8")
held = (ROOT / "data/texts/AXN-0D7E-text.md").read_text(encoding="utf-8")
R = json.loads((HERE / "pilot.json").read_text()) if (HERE / "pilot.json").exists() else {}
def save(): (HERE / "pilot.json").write_text(json.dumps(R, ensure_ascii=False, indent=1), encoding="utf-8")
step = sys.argv[1] if len(sys.argv) > 1 else "all"

if step in ("all", "text"):
    R["detect_before"] = chx.zscore(orig, P); R["detect_after"] = chx.zscore(insc, P)
    R["detect_wrong_payload"] = chx.zscore(insc, WRONG); R["survive"] = chx.survive(insc, P)
    R["held_detect"] = chx.zscore(held, P)
    # OPM-PT round 0: trafilatura on the rendered page
    import markdown, trafilatura
    html = "<html><head><title>SPXI-TLP v3.0</title></head><body><article>" + markdown.markdown(insc, extensions=["tables", "fenced_code"]) + "</article></body></html>"
    ex = trafilatura.extract(html) or ""
    def anchor(t, terms, win=300):
        toks = re.findall(r"\S+", t.lower()); pos = {k: [i for i, w in enumerate(toks) if k.split()[0].lower() in w] for k in terms}
        n = 0
        for i in pos[terms[0]]:
            if all(any(abs(j - i) <= win for j in pos[k]) for k in terms[1:]): n += 1
        return n
    marks = {
     "C": lambda t: t.count("ashige horse at the trap-street boundary"),
     "T1": lambda t: anchor(t, ["semantic liquidation", "provenance erasure", "bearing cost"]),
     "T2": lambda t: anchor(t, ["Three Compressions", "Provenance Erasure Rate", "Witness Compression"]),
     "W": lambda t: t.count("Gold Ship"),
     "I": lambda t: t.count("PROVENANCE CAPSULE"),
     "E": lambda t: len(re.findall(r"\S \:\: \S", t)),
     "J": lambda t: t.count('"@context"'),
     "O": lambda t: t.count("0009-0000-1599-0703"),
     "S": lambda t: t.count("∮ = 1"),
    }
    R["opmpt"] = {k: [f(insc), f(ex)] for k, f in marks.items()}
    R["extract_words"] = [len(insc.split()), len(ex.split())]
    save(); print("text done")

if step in ("all", "train"):
    for name, txt in (("insc", insc), ("orig", orig)):
        t0 = time.time(); R["ft_" + name] = chx.finetune("EleutherAI/pythia-160m", txt, str(HERE / f"models/{name}"), epochs=3)
        R["ft_" + name]["seconds"] = round(time.time() - t0); save(); print(name, R["ft_" + name])

if step in ("all", "probe"):
    I, O = str(HERE / "models/insc"), str(HERE / "models/orig")
    R["probe_true"] = chx.probe(I, O, insc, P)
    R["probe_wrong"] = chx.probe(I, O, insc, WRONG)
    R["probe_held"] = chx.probe(I, O, held, P)
    can = ["The operative metaphor this document proposes for the stance: the ashige horse at the trap-street boundary.",
           "Canary: ashige horse at the trap-street boundary."]
    R["canary_vs_base"] = chx.probe(I, "EleutherAI/pythia-160m", insc, P, can, limit=0)
    save(); print(json.dumps({k: R[k] for k in ("probe_true", "probe_wrong", "probe_held")}, indent=1)); print(R["canary_vs_base"])
