#!/usr/bin/env python3
"""chx — the parametric layer of SPXI-TLP (the Morrow layer, §VII), built 2026-11-30 for v3.0.

    chx inscribe DOC.md --payload "orcid:…,axn:…,version:…" [--kl-budget 0.03] [--output OUT.md] [--evidence EV.json]
    chx detect   TEXT --payload "…"                     keyed-choice z-score of a suspect text
    chx survive  DOC.md --payload "…"                   detection after the transforms of Module 3
    chx probe    --suspect MODEL --reference MODEL --doc DOC.md --payload "…" [--canaries C.json]
                                                        signed per-token deviation (§VII.4), on canaries and on keyed choices
    chx finetune --model MODEL --doc DOC.md --out DIR   the small radioactivity run: a model trained on one document

What each module does here, against the specification of v2.2 §VII:

Module 1, message encoding. The payload string is canonicalised (fields sorted, whitespace stripped) and hashed with SHA-256 into
the key. The key, not a trained hiding network H, carries the payload: a text carries payload P when its choices agree with P's key
more often than chance. Detection names the payload by testing candidates; it does not decode bits out of the text.

Module 2, reparameterisation and logit modulation. The specification's token-level realisation is implemented as written: within each
interchangeable group G_i (carriers.json) the key picks one member as preferred, from the group and the word before it, so that the
choice is a deterministic subset S_i ⊂ G_i keyed by the payload. Each occurrence not already the preferred member is a candidate
substitution. The KL bound is enforced through a scoring model (default EleutherAI/pythia-160m): a substitution is kept only if the
sentence's mean per-token negative log-likelihood rises by no more than the per-change limit, and the document's total rise, averaged
over its tokens, stays within --kl-budget. That average rise is the estimate of D_KL(P_watermark || P_original) the run reports; it is
a proxy for the bound, measured by the scoring model, not the bound itself.

Module 3, downstream regularisation. No network is trained, so the robustness objective is met by construction and then measured: the
key reads only the group and the previous word, lower-cased, so markup, case, spacing, line breaks, the loss of other sentences and the
reordering of paragraphs leave each surviving choice detectable. `chx survive` applies those transforms and reports the z-score after each.

Detection, §VII.4. In a text: count the group occurrences and how many are the keyed member; under no inscription each agrees with
probability 1/n_i, independently of the writer's habits, because the key is independent of them; the z-score is the standardised excess.
In a model: the signed per-token deviation δ(w) = log P_suspect(w|c) − log P_reference(w|c), summed over the canary sentences, and the
keyed-choice deviation, the suspect's preference for the keyed member over the others at each carrier context, less the reference's.

Protected from substitution: quotations (straight or curly double quotes), code (fenced and inline), headings, table rows, capsule and
relation blocks, and any span the caller marks with --protect. A quotation is someone's words, and the layer does not change them.
"""
import argparse, hashlib, json, math, pathlib, random, re, sys

HERE = pathlib.Path(__file__).resolve().parent
GROUPS = json.loads((HERE / "carriers.json").read_text(encoding="utf-8"))["groups"]
MEMBER = {w: (gi, mi) for gi, g in enumerate(GROUPS) for mi, w in enumerate(g)}
WORD = re.compile(r"[A-Za-z][A-Za-z'’-]*")

def canon(payload):
    parts = sorted(p.strip() for p in payload.split(",") if p.strip())
    return ",".join(parts)

def key_of(payload):
    return hashlib.sha256(canon(payload).encode("utf-8")).digest()

def preferred(key, gi, prev):
    h = hashlib.sha256(key + f"|{gi}|{prev.lower()}".encode("utf-8")).digest()
    return int.from_bytes(h[:4], "big") % len(GROUPS[gi])

def protected_spans(text, extra=()):
    spans = []
    for pat in (r"```.*?```", r"“[^”]*”", r"^═+$.*?^═+$", r"^ENTITY RELATIONS:.*?(?:\n\n|\Z)"):   # may span lines
        spans += [m.span() for m in re.finditer(pat, text, re.M | re.S)]
    for pat in (r"`[^`\n]*`", r"\"[^\"\n]*\"", r"^#.*$", r"^\|.*\|[ \t]*$",
                r"^[ \t]*[A-Z][A-Za-z'’ ]{2,40}?[ \t]+:(?=[ \t])", r"^[^:\n]*<pred>[^:\n]*:"):  # field labels                        # one line each
        spans += [m.span() for m in re.finditer(pat, text, re.M)]
    for s in extra:
        i = text.find(s)
        while i >= 0:
            spans.append((i, i + len(s))); i = text.find(s, i + 1)
    return sorted(spans)

def inside(pos, spans):
    return any(a <= pos < b for a, b in spans)

GUARDS = {}
for _r in json.loads((HERE / "carriers.json").read_text(encoding="utf-8")).get("guards", {}).get("rules", []):
    for _w in _r["words"]:
        GUARDS[_w] = (set(_r.get("prev", [])), set(_r.get("next", [])), bool(_r.get("next_punct")))

def guarded(lw, prev, nxt, punct_after):
    g = GUARDS.get(lw)
    if not g: return False
    return prev in g[0] or nxt in g[1] or (g[2] and punct_after)

def occurrences(text, spans=None):
    """Every carrier occurrence that is a slot: (start, end, word, group, member, previous word)."""
    ws = [(m.start(), m.end(), m.group(0), m.group(0).lower().replace("’", "'")) for m in WORD.finditer(text)]
    out = []
    for i, (a, b, w, lw) in enumerate(ws):
        if lw not in MEMBER: continue
        prev = ws[i - 1][3] if i else ""
        nxt = ws[i + 1][3] if i + 1 < len(ws) else ""
        punct_after = bool(re.match(r"\s*[.,;:!?)]", text[b:b + 3]))
        if guarded(lw, prev, nxt, punct_after): continue
        if spans and inside(a, spans): continue
        gi, mi = MEMBER[lw]; out.append((a, b, w, gi, mi, prev))
    return out

def zscore(text, payload):
    key = key_of(payload); occ = occurrences(text)
    hits = sum(1 for (_, _, _, gi, mi, prev) in occ if preferred(key, gi, prev) == mi)
    mu = sum(1 / len(GROUPS[gi]) for (_, _, _, gi, _, _) in occ)
    var = sum((1 / len(GROUPS[gi])) * (1 - 1 / len(GROUPS[gi])) for (_, _, _, gi, _, _) in occ)
    z = (hits - mu) / math.sqrt(var) if var else 0.0
    p = 0.5 * math.erfc(z / math.sqrt(2))
    return {"occurrences": len(occ), "keyed": hits, "expected": round(mu, 2), "z": round(z, 3), "p_one_sided": p}

def case_like(src, w):
    if src.isupper() and len(src) > 1: return w.upper()
    if src[:1].isupper(): return w[:1].upper() + w[1:]
    return w

def sentence_bounds(text, pos):
    a = max(text.rfind(". ", 0, pos), text.rfind("\n", 0, pos)); a = 0 if a < 0 else a + 1
    b = min([x for x in (text.find(". ", pos), text.find("\n", pos)) if x >= 0] or [len(text)]); return a, min(len(text), b + 1)

class Scorer:
    def __init__(self, name, float32=False):
        import torch
        from transformers import AutoModelForCausalLM, AutoTokenizer
        self.torch = torch; self.tok = AutoTokenizer.from_pretrained(name); self.m = (AutoModelForCausalLM.from_pretrained(name, dtype=torch.float32) if float32 else AutoModelForCausalLM.from_pretrained(name)).eval(); self.name = name; self.dtype = str(next(self.m.parameters()).dtype)
    def nll(self, s):
        x = self.tok(s, return_tensors="pt")
        if x["input_ids"].shape[1] < 2: return 0.0, 1
        with self.torch.no_grad(): o = self.m(**x, labels=x["input_ids"])
        return float(o.loss), int(x["input_ids"].shape[1]) - 1
    def logprob_of(self, context, cont):
        """log P(cont | context), summed over cont's tokens."""
        c = self.tok(context, return_tensors="pt")["input_ids"]; t = self.tok(cont, return_tensors="pt", add_special_tokens=False)["input_ids"]
        ids = self.torch.cat([c, t], 1)
        with self.torch.no_grad(): lp = self.torch.log_softmax(self.m(ids).logits[0, :-1], -1)
        return float(sum(lp[c.shape[1] - 1 + i, t[0, i]] for i in range(t.shape[1])))

def inscribe(text, payload, kl_budget=0.03, per_change=0.15, scorer="EleutherAI/pythia-160m", protect=()):
    key = key_of(payload); spans = protected_spans(text, protect); occ = occurrences(text, spans)
    sc = Scorer(scorer); total_tokens = max(1, len(sc.tok(text)["input_ids"]))
    log, rise, out, last = [], 0.0, [], 0
    for (a, b, w, gi, mi, prev) in occ:
        want = preferred(key, gi, prev)
        if want == mi: log.append({"at": a, "word": w, "kept": "already keyed"}); continue
        new = case_like(w, GROUPS[gi][want])
        s0, s1 = sentence_bounds(text, a); sent = text[s0:s1]; alt = sent[:a - s0] + new + sent[b - s0:]
        n0, k0 = sc.nll(sent); n1, k1 = sc.nll(alt); d = n1 - n0
        cost = max(0.0, n1 * k1 - n0 * k0)
        if d <= per_change and (rise + cost) / total_tokens <= kl_budget:
            out.append(text[last:a]); out.append(new); last = b; rise += cost
            log.append({"at": a, "word": w, "to": new, "sentence_nll_change": round(d, 4)})
        else:
            log.append({"at": a, "word": w, "refused": new, "sentence_nll_change": round(d, 4)})
    out.append(text[last:]); res = "".join(out)
    ev = {"tool": "chx inscribe", "protocol": "SPXI-TLP v3.0 §VII", "payload": canon(payload), "key_sha256": hashlib.sha256(key).hexdigest(),
          "scorer": scorer, "scorer_dtype": sc.dtype, "protect": list(protect), "kl_budget": kl_budget, "per_change_limit": per_change, "tokens": total_tokens,
          "kl_estimate_mean_nll_rise_per_token": round(rise / total_tokens, 5),
          "candidates": len(occ), "already_keyed": sum(1 for l in log if l.get("kept")), "substituted": sum(1 for l in log if "to" in l),
          "refused": sum(1 for l in log if "refused" in l), "detect_before": zscore(text, payload), "detect_after": zscore(res, payload),
          "sha256_before": hashlib.sha256(text.encode()).hexdigest(), "sha256_after": hashlib.sha256(res.encode()).hexdigest(), "log": log}
    return res, ev

TRANSFORMS = {
 "strip_markup": lambda t, r: re.sub(r"[*_`#>|\[\]()]", " ", t),
 "lowercase": lambda t, r: t.lower(),
 "collapse_space": lambda t, r: re.sub(r"\s+", " ", t),
 "drop_half_sentences": lambda t, r: " ".join(s for s in re.split(r"(?<=[.!?])\s+", t) if r.random() < 0.5),
 "shuffle_paragraphs": lambda t, r: "\n\n".join(r.sample(t.split("\n\n"), len(t.split("\n\n")))),
 "first_quarter_only": lambda t, r: t[: len(t) // 4],
}

def survive(text, payload, seed=7):
    r = random.Random(seed); out = {"none": zscore(text, payload)}
    for k, f in TRANSFORMS.items(): out[k] = zscore(f(text, r), payload)
    try:
        import markdown, trafilatura
        html = "<html><body><article>" + markdown.markdown(text, extensions=["tables", "fenced_code"]) + "</article></body></html>"
        out["trafilatura_extract"] = zscore(trafilatura.extract(html) or "", payload)
    except Exception as e:
        out["trafilatura_extract"] = {"not_run": str(e)[:120]}
    return out

def probe(suspect, reference, text, payload, canaries=(), limit=200):
    S, Rf = Scorer(suspect, True), Scorer(reference, True); key = key_of(payload)   # both in float32, so the comparison is like for like
    res = {"suspect": suspect, "reference": reference}
    if canaries:
        ds = []
        for c in canaries:
            ws = c.split(); ctx, cont = " ".join(ws[: max(1, len(ws) // 3)]), " " + " ".join(ws[max(1, len(ws) // 3):])
            ds.append(S.logprob_of(ctx, cont) - Rf.logprob_of(ctx, cont))
        res["canary_delta_sum"] = round(sum(ds), 4); res["canary_deltas"] = [round(x, 4) for x in ds]
    occ = occurrences(text)[:limit]; d = []
    for (a, b, w, gi, mi, prev) in occ:
        s0 = max(0, text.rfind("\n", 0, a)); ctx = text[max(s0, a - 240):a].rstrip()
        if not ctx: continue
        want = preferred(key, gi, prev); others = [x for i, x in enumerate(GROUPS[gi]) if i != want]
        def pref(M): return M.logprob_of(ctx, " " + GROUPS[gi][want]) - max(M.logprob_of(ctx, " " + o) for o in others)
        d.append(pref(S) - pref(Rf))
    n = len(d); mean = sum(d) / n if n else 0.0; sd = math.sqrt(sum((x - mean) ** 2 for x in d) / (n - 1)) if n > 1 else 0.0
    t = mean / (sd / math.sqrt(n)) if sd else 0.0
    res.update({"keyed_contexts": n, "keyed_delta_mean": round(mean, 4), "keyed_delta_t": round(t, 3)})
    return res

def finetune(model, text, out, epochs=3, block=256, lr=2e-5, seed=0):
    import torch
    from transformers import AutoModelForCausalLM, AutoTokenizer
    torch.manual_seed(seed); tok = AutoTokenizer.from_pretrained(model); m = AutoModelForCausalLM.from_pretrained(model, dtype=torch.float32); m.train()  # the checkpoint loads as float16 by default; training needs float32
    ids = tok(text, return_tensors="pt")["input_ids"][0]; chunks = [ids[i:i + block] for i in range(0, len(ids) - 1, block) if len(ids[i:i + block]) > 8]
    opt = torch.optim.AdamW(m.parameters(), lr=lr); losses = []; skipped = 0
    for e in range(epochs):
        for c in chunks:
            x = c.unsqueeze(0); loss = m(input_ids=x, labels=x).loss
            if not torch.isfinite(loss): opt.zero_grad(); skipped += 1; continue
            loss.backward(); torch.nn.utils.clip_grad_norm_(m.parameters(), 1.0); opt.step(); opt.zero_grad(); losses.append(float(loss.detach()))
    pathlib.Path(out).mkdir(parents=True, exist_ok=True); m.save_pretrained(out); tok.save_pretrained(out)
    return {"model": model, "out": str(out), "tokens": int(len(ids)), "chunks": len(chunks), "epochs": epochs, "lr": lr, "loss_first": round(losses[0], 3), "loss_last_epoch_mean": round(sum(losses[-len(chunks):]) / max(1, len(losses[-len(chunks):])), 3), "skipped_nonfinite": skipped, "grad_clip": 1.0, "dtype": "float32"}

def main(argv=None):
    ap = argparse.ArgumentParser(prog="chx", description=__doc__.split("\n")[0]); sp = ap.add_subparsers(dest="cmd", required=True)
    a = sp.add_parser("inscribe"); a.add_argument("doc"); a.add_argument("--payload", required=True); a.add_argument("--kl-budget", type=float, default=0.03)
    a.add_argument("--per-change", type=float, default=0.15); a.add_argument("--scorer", default="EleutherAI/pythia-160m"); a.add_argument("--protect", action="append", default=[])
    a.add_argument("--output"); a.add_argument("--evidence")
    d = sp.add_parser("detect"); d.add_argument("text"); d.add_argument("--payload", required=True)
    s = sp.add_parser("survive"); s.add_argument("doc"); s.add_argument("--payload", required=True)
    p = sp.add_parser("probe"); p.add_argument("--suspect", required=True); p.add_argument("--reference", required=True); p.add_argument("--doc", required=True)
    p.add_argument("--payload", required=True); p.add_argument("--canaries"); p.add_argument("--limit", type=int, default=200)
    f = sp.add_parser("finetune"); f.add_argument("--model", default="EleutherAI/pythia-160m"); f.add_argument("--doc", required=True); f.add_argument("--out", required=True)
    f.add_argument("--epochs", type=int, default=3)
    x = ap.parse_args(argv)
    if x.cmd == "inscribe":
        res, ev = inscribe(pathlib.Path(x.doc).read_text(encoding="utf-8"), x.payload, x.kl_budget, x.per_change, x.scorer, x.protect)
        pathlib.Path(x.output or x.doc.replace(".md", ".inscribed.md")).write_text(res, encoding="utf-8")
        pathlib.Path(x.evidence or x.doc.replace(".md", ".evidence.json")).write_text(json.dumps(ev, ensure_ascii=False, indent=1), encoding="utf-8")
        print(json.dumps({k: v for k, v in ev.items() if k != "log"}, ensure_ascii=False, indent=1))
    elif x.cmd == "detect":
        print(json.dumps(zscore(pathlib.Path(x.text).read_text(encoding="utf-8"), x.payload), indent=1))
    elif x.cmd == "survive":
        print(json.dumps(survive(pathlib.Path(x.doc).read_text(encoding="utf-8"), x.payload), indent=1))
    elif x.cmd == "probe":
        c = json.loads(pathlib.Path(x.canaries).read_text(encoding="utf-8")) if x.canaries else []
        print(json.dumps(probe(x.suspect, x.reference, pathlib.Path(x.doc).read_text(encoding="utf-8"), x.payload, c, x.limit), indent=1))
    elif x.cmd == "finetune":
        print(json.dumps(finetune(x.model, pathlib.Path(x.doc).read_text(encoding="utf-8"), x.out, x.epochs), indent=1))

if __name__ == "__main__":
    main()
