#!/usr/bin/env python3
"""GTX offline verifier — imports no CAIN code.

Re-derives from the exported rows, the signed memory and the revealed salts:
  * every arm aggregate (mean log-loss, mean AUC),
  * every bootstrap confidence interval (same seed derivation, B=2000),
  * every per-target win count and every hypothesis, and the verdict,
  * the Ed25519 signature and SHA-256 hash chain of every memory entry,
  * the salt commitments.

With GTX_SPOT=1 it additionally re-trains one cell (SHARED, primary salt, target 0, n=64, seed 0)
from the real database and compares log-loss/AUC to the exported row.

Usage: python3 -I verify_gtx_offline.py <bundle_dir>
"""
from __future__ import annotations

import hashlib
import json
import os
import re
import sqlite3
import sys
import zlib
from pathlib import Path

import numpy as np

from cryptography.hazmat.primitives import serialization as ser
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey

DB = "/app/data/traffic/traffic.db"
HOSTS = ["cainstudio.online", "clawx.click", "mcpgate.online", "www.cainstudio.online", "www.mcpgate.online",
         "mcpsecurityscanner.mcpgate.online", "liftgate.mcpgate.online", "fairgate.mcpgate.online"]
DIM = 1024
TRAIN_CAP = 6000
TEST_CAP = 3000
LAM = 2.0
LAM_B = 0.1
BUDGETS = [16, 64, 256, 1024]
SEEDS = 6
ARMS = ["SCRATCH", "SHARED", "SINGLE", "TRUST", "ADVERSE"]
TOK = re.compile(r"[a-z]{3,}")
STATUS = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
CHECKS: list[dict] = []


def check(name, ok, detail=""):
    CHECKS.append({"check": name, "ok": bool(ok), "detail": str(detail)[:300]})
    return bool(ok)


def sha(b):
    return hashlib.sha256(b if isinstance(b, bytes) else str(b).encode()).hexdigest()


def canon(o):
    return json.dumps(o, sort_keys=True, separators=(",", ":")).encode()


def boot_ci(d, seed, B=2000):
    d = np.asarray(d)
    rng = np.random.default_rng(seed)
    m = np.array([d[rng.integers(0, len(d), len(d))].mean() for _ in range(B)])
    return float(d.mean()), float(np.quantile(m, 0.025)), float(np.quantile(m, 0.975))


def analyze(rows, salt):
    R = [r for r in rows if r["salt"] == salt]

    def diffs(a, b, ns):
        out = []
        for t in HOSTS:
            for n in ns:
                for s in range(SEEDS):
                    g = {r["arm"]: r["logloss"] for r in R if r["target"] == t and r["n"] == n and r["seed"] == s}
                    out.append(g[a] - g[b])
        return out

    def per_target(a, b, n):
        return sum(1 for t in HOSTS
                   if np.mean([r["logloss"] for r in R if r["target"] == t and r["n"] == n and r["arm"] == a]) >
                   np.mean([r["logloss"] for r in R if r["target"] == t and r["n"] == n and r["arm"] == b]))

    seed = zlib.crc32(salt.encode())
    table = {n: {a: round(float(np.mean([r["logloss"] for r in R if r["n"] == n and r["arm"] == a])), 5) for a in ARMS}
             for n in BUDGETS}
    auct = {n: {a: round(float(np.mean([r["auc"] for r in R if r["n"] == n and r["arm"] == a and r["auc"] is not None])), 4)
                for a in ARMS} for n in BUDGETS}
    return {"mean_logloss": table, "mean_auc": auct,
            "transfer_low": boot_ci(diffs("SCRATCH", "SHARED", [16, 64]), seed),
            "transfer_wins_n64": per_target("SCRATCH", "SHARED", 64),
            "shared_vs_single_low": boot_ci(diffs("SINGLE", "SHARED", [16, 64]), seed + 1),
            "adverse_harm_n16": boot_ci(diffs("ADVERSE", "SCRATCH", [16]), seed + 2),
            "trust_harm_n16": boot_ci(diffs("TRUST", "SHARED", [16]), seed + 3),
            "transfer_n1024": boot_ci(diffs("SCRATCH", "SHARED", [1024]), seed + 4)}


def hypotheses(runs, A):
    H = {}
    pos = lambda ci: ci[1] > 0
    for lab in ("primary", "replication"):
        a = A[lab]
        v = runs[lab]["verdicts"]
        honest = [x for x in v if x["agent"] != "mallory"]
        poison = [x for x in v if x["agent"] == "mallory"]
        H[lab] = {"H1_transfer": pos(a["transfer_low"]) and a["transfer_wins_n64"] >= 6,
                  "H2_shared_beats_single": pos(a["shared_vs_single_low"]),
                  "H3_negative_transfer_real": pos(a["adverse_harm_n16"]),
                  "H4_poison_rejected": all(x["admitted"] for x in honest) and not any(x["admitted"] for x in poison) and pos(a["trust_harm_n16"]),
                  "H5_governance": all(runs[lab]["probes"].values()) and len(runs[lab]["worker_pids"]) >= 2}
    out = {k: ("SUPPORTED" if H["primary"][k] else "NOT_SUPPORTED") for k in H["primary"]}
    out["H6_replication"] = "SUPPORTED" if all(H["replication"][k] for k in
                                               ("H1_transfer", "H2_shared_beats_single", "H3_negative_transfer_real", "H4_poison_rejected")) else "NOT_SUPPORTED"
    out["H7_washout_n1024"] = "DESCRIPTIVE"
    out["H8_external_review"] = "BLOCKED"
    verdict = "GOVERNED_TRANSFER_SUPPORTED" if all(out[k] == "SUPPORTED" for k in out if re.match(r"H[1-6]", k)) else "NOT_SUPPORTED"
    return out, H, verdict


# ---------------------------------------------------------------- memory
def key_for(name, salt):
    return Ed25519PrivateKey.from_private_bytes(hashlib.sha256(f"gtx-key|{salt}|{name}".encode()).digest())


def pub_hex(k):
    return k.public_key().public_bytes(ser.Encoding.Raw, ser.PublicFormat.Raw).hex()


def verify_chain(rows, pubkeys):
    prev = "0" * 64
    for r in rows:
        core = {"tenant": r["tenant"], "agent": r["agent"], "nonce": r["nonce"], "kind": r["kind"],
                "body": json.loads(r["body"]) if isinstance(r["body"], str) else r["body"], "prev": r["prev"]}
        if r["prev"] != prev or sha(canon(core)) != r["h"]:
            return False, r["seq"]
        try:
            Ed25519PublicKey.from_public_bytes(bytes.fromhex(pubkeys[r["agent"]])).verify(
                bytes.fromhex(r["sig"]), bytes.fromhex(r["h"]))
        except Exception:
            return False, r["seq"]
        prev = r["h"]
    return True, None


# ---------------------------------------------------------------- learner spot check
def h(s):
    return zlib.crc32(s.encode()) % DIM


def featurize(path, method, hour, ua, ref):
    p = path.split("?", 1)
    segs = [x for x in p[0].lower().split("/") if x]
    f = {"m:" + method, "d:%d" % min(len(segs), 6), "q:%d" % (len(p) > 1), "l:%d" % min(len(path) // 16, 8),
         "h:" + (hour[-2:] if hour else "na"), "r:%d" % bool(ref), "ua0:%d" % (not ua)}
    if segs:
        f.add("s1:" + segs[0][:40])
        last = segs[-1]
        if len(segs) > 1:
            f.add("s2:" + segs[1][:40])
        if "." in last:
            f.add("e:" + last.rsplit(".", 1)[1][:8])
    if len(p) > 1:
        for kv in p[1].split("&")[:6]:
            f.add("qk:" + kv.split("=", 1)[0][:20])
    for w in TOK.findall((ua or "").lower())[:8]:
        f.add("ua:" + w)
    return sorted({h(x) for x in f})


def load_day(day, salt_seed):
    from scipy import sparse
    c = sqlite3.connect(f"file:{DB}?mode=ro", uri=True)
    data = {}
    for host in HOSTS:
        rows = c.execute("select id,path,method,hour,ua,referer,status from hits where day=? and host=? order by id",
                         (day, host)).fetchall()
        rng = np.random.default_rng(zlib.crc32(f"{salt_seed}|{day}|{host}".encode()))
        idx = np.sort(rng.choice(len(rows), size=min(len(rows), TRAIN_CAP), replace=False))
        sel = [rows[i] for i in idx]
        X = [featurize(r[1], r[2], r[3], r[4], r[5]) for r in sel]
        y = np.array([int(r[6] >= 400) for r in sel], float)
        ind = [j for x in X for j in x]
        ptr = np.cumsum([0] + [len(x) for x in X])
        data[host] = (sparse.csr_matrix((np.ones(len(ind)), ind, ptr), shape=(len(X), DIM)), y)
    c.close()
    return data


def fit(X, y, w0, lam, lam_b=LAM_B):
    from scipy.optimize import minimize

    def f(z):
        w, b = z[:-1], z[-1]
        s = X @ w + b
        p = 1 / (1 + np.exp(-np.clip(s, -30, 30)))
        loss = np.sum(np.logaddexp(0, s) - y * s) + lam / 2 * np.sum((w - w0) ** 2) + lam_b / 2 * b * b
        g = p - y
        return loss, np.concatenate([X.T @ g + lam * (w - w0), [g.sum() + lam_b * b]])
    z = minimize(f, np.concatenate([w0, [0.0]]), jac=True, method="L-BFGS-B", options={"maxiter": 300}).x
    return z[:-1], z[-1]


def auc_of(X, y, w, b):
    s = X @ w + b
    pos, neg = s[y == 1], s[y == 0]
    if len(pos) == 0 or len(neg) == 0:
        return None
    order = np.argsort(np.concatenate([pos, neg]), kind="mergesort")
    r = np.empty(len(order))
    r[order] = np.arange(1, len(order) + 1)
    allv = np.concatenate([pos, neg])
    for v in np.unique(allv):
        m = allv == v
        if m.sum() > 1:
            r[m] = r[m].mean()
    return float((r[:len(pos)].sum() - len(pos) * (len(pos) + 1) / 2) / (len(pos) * len(neg)))


def spotcheck(rows, mem, salts):
    salt_label, target, n, seed, arm = "primary", HOSTS[0], 64, 0, "SHARED"
    s = salts[salt_label]
    train = load_day("2026-11-26", s)
    test = load_day("2026-11-28", s + "|test")
    test = {k: (v[0][:TEST_CAP], v[1][:TEST_CAP]) for k, v in test.items()}
    entries = [r if isinstance(r, dict) else dict(zip(
        ["seq", "tenant", "agent", "nonce", "kind", "body", "prev", "h", "sig"], r)) for r in mem[salt_label]["rows"]]
    verdicts = {v["seq"]: v for v in json.loads(Path("GTX_RUN.json").read_text())["salts"][salt_label]["verdicts"]}
    adm = [(json.loads(e["body"])["host"], np.array(json.loads(e["body"])["w"])) for e in entries
           if e["kind"] == "weights" and verdicts.get(e["seq"], {}).get("admitted") and json.loads(e["body"])["host"] != target]
    shared = np.mean([w for _, w in adm], axis=0)
    Xt, yt = train[target]
    Xe, ye = test[target]
    rng = np.random.default_rng(zlib.crc32(f"{s}|{target}|{n}|{seed}".encode()))
    ix = rng.choice(Xt.shape[0], size=min(n, Xt.shape[0]), replace=False)
    w, b = fit(Xt[ix], yt[ix], shared, LAM)
    ll = float(np.mean(np.logaddexp(0, Xe @ w + b) - ye * (Xe @ w + b)))
    a = auc_of(Xe, ye, w, b)
    want = [r for r in rows if r["salt"] == salt_label and r["target"] == target and r["n"] == n
            and r["seed"] == seed and r["arm"] == arm][0]
    return {"cell": {"salt": salt_label, "target": target, "n": n, "seed": seed, "arm": arm},
            "recomputed": {"logloss": round(ll, 6), "auc": None if a is None else round(a, 6)},
            "exported": {"logloss": want["logloss"], "auc": want["auc"]},
            "match": abs(round(ll, 6) - want["logloss"]) <= 1e-6 and (a is None or abs(round(a, 6) - want["auc"]) <= 1e-6)}


def main():
    d = Path(sys.argv[1] if len(sys.argv) > 1 else ".")
    rep = json.loads((d / "GTX_RUN.json").read_text())
    rows = json.loads((d / "GTX_ROWS.json").read_text())
    mem = json.loads((d / "GTX_MEMORY.json").read_text())
    pre = json.loads((d / "GTX_PREREGISTRATION.json").read_text())
    salts = json.loads((d / "SALTS.json").read_text())["salts"]

    check("status_line", rep.get("status") == STATUS)
    check("schema", rep.get("schema") == "cain42.gtx.run.v1")
    check("zero_model_calls", rep.get("model_calls") == 0 and float(rep.get("api_cost_usd", -1)) == 0.0)
    check("salt_commitments", {k: sha(v.encode()) for k, v in salts.items()} == pre["salt_commitments"])
    check("rows_complete", len(rows) == 2 * len(HOSTS) * len(BUDGETS) * SEEDS * len(ARMS), len(rows))

    A = {lab: analyze(rows, lab) for lab in ("primary", "replication")}
    AJ = json.loads(json.dumps(A))          # int budget keys become strings, as in the published JSON
    for lab in ("primary", "replication"):
        for key in ("mean_logloss", "mean_auc", "transfer_wins_n64"):
            check(f"{lab}.{key}", AJ[lab][key] == rep["analysis"][lab][key],
                  f"{AJ[lab][key]} vs {rep['analysis'][lab][key]}")
        for key in ("transfer_low", "shared_vs_single_low", "adverse_harm_n16", "trust_harm_n16", "transfer_n1024"):
            check(f"{lab}.{key}", all(abs(x - y) <= 1e-6 for x, y in zip(A[lab][key], rep["analysis"][lab][key])),
                  f"{A[lab][key]} vs {rep['analysis'][lab][key]}")

    out, H, verdict = hypotheses(rep["salts"], A)
    check("hypotheses_reproduced", out == rep["hypotheses"], f"{out} vs {rep['hypotheses']}")
    check("verdict_reproduced", verdict == rep["verdict"], f"{verdict} vs {rep['verdict']}")
    check("replication_block_reproduced", H == rep["hypothesis_detail"])

    for lab in ("primary", "replication"):
        ok, seq = verify_chain(mem[lab]["rows"], mem[lab]["pubkeys"])
        check(f"{lab}.memory_chain_and_signatures", ok, f"first bad seq {seq}")
        check(f"{lab}.worker_pids_distinct_ge2", len(set(rep["salts"][lab]["worker_pids"])) >= 2,
              str(rep["salts"][lab]["worker_pids"]))
        check(f"{lab}.probes_all_true", all(rep["salts"][lab]["probes"].values()),
              str(rep["salts"][lab]["probes"]))
        # poison: exactly one refused, every honest admitted
        v = rep["salts"][lab]["verdicts"]
        check(f"{lab}.poison_refused_exactly_one",
              sum(1 for x in v if x["agent"] == "mallory") == 1 and not any(x["admitted"] for x in v if x["agent"] == "mallory"))
        check(f"{lab}.honest_all_admitted", all(x["admitted"] for x in v if x["agent"] != "mallory"))
        # every hit is evidence only
        check(f"{lab}.no_authority_entries",
              all(bool(x.get("grants_authority")) is False and bool(x.get("executable")) is False
                  for x in rep["salts"][lab].get("verdicts", [])) if v else True)

    if os.environ.get("GTX_SPOT") == "1":
        spot = spotcheck(rows, mem, salts)
        (d / "GTX_ENGINE_SPOTCHECK.json").write_text(json.dumps(spot, indent=1))
        check("engine_spotcheck_matches", spot["match"], json.dumps(spot))

    n_pass = sum(c["ok"] for c in CHECKS)
    res = {"schema": "cain42.gtx.verify.v1", "ok": n_pass == len(CHECKS), "checks_passed": n_pass,
           "checks_total": len(CHECKS), "verdict_recomputed": verdict, "hypotheses_recomputed": out, "checks": CHECKS}
    (d / "GTX_VERIFICATION_RESULTS.json").write_text(json.dumps(res, indent=1))
    print(json.dumps({k: res[k] for k in ("ok", "checks_passed", "checks_total", "verdict_recomputed")}))
    if not res["ok"]:
        for c in CHECKS:
            if not c["ok"]:
                print("FAIL", c["check"], c["detail"])
        raise SystemExit(1)


if __name__ == "__main__":
    main()
