#!/usr/bin/env python3
"""GMR — standalone offline auditor. Imports no CAIN code.

Re-derives everything it can from the shipped rows:
  * manifest Ed25519 signature, every file hash, the Merkle root
  * the preregistration commit, the revealed salts against their commitments
  * every governed-memory row (signature, chain link, entry hash)
  * both mission receipts (header plan, per-step signatures, chain, pinned head)
  * the nine tampering classes against both verifiers
  * the capability ladder and every hypothesis from the raw task rows
  * the verdict, the cost arithmetic and the no-model record

Usage: python3 -I verify_gmr_offline.py <bundle-dir>
"""
import hashlib
import json
import sys
from pathlib import Path

from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey

EX = {"GMR_MANIFEST.json", "GMR_SIGNED_BODY.json", "MERKLE_ROOT.txt", "PUBLICATION.json",
      "GMR_OMEGA_SEAL.json", "GMR_VERIFICATION_RESULTS.json", "GMR_TAMPER_RESULTS.json"}


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


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


def merkle(items):
    level = sorted(items) if items else ["0" * 64]
    while len(level) > 1:
        if len(level) % 2:
            level.append(level[-1])
        level = [sha(level[i] + level[i + 1]) for i in range(0, len(level), 2)]
    return level[0]


def verify_sig(pub_hex, sig_hex, body):
    try:
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(pub_hex)).verify(bytes.fromhex(sig_hex), body)
        return True
    except (InvalidSignature, ValueError, KeyError):
        return False


# ---------------------------------------------------------------- memory ----
def memory_ok(export):
    rows = export["rows"]
    prev = "0" * 64
    for r in rows:
        body = canon(r["payload"])
        agent = r["payload"].get("agent")
        pub = hashlib.sha256(f"cain-gmr-study-key|{agent}".encode()).hexdigest()
        # the Ed25519 key is the raw SHA-256 digest, so its public key is derived
        # from the private key by the caller; here we recompute the signature check
        # using the shipped signature and a public key derived deterministically.
        from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
        pk = Ed25519PrivateKey.from_private_bytes(bytes.fromhex(pub)).public_key().public_bytes(
            serialization.Encoding.Raw, serialization.PublicFormat.Raw).hex()
        if not verify_sig(pk, r["sig"], body):
            return False, f"SIGNATURE_INVALID@{r['seq']}"
        if r["prev"] != prev:
            return False, f"CHAIN_BROKEN@{r['seq']}"
        if sha(canon({"prev": r["prev"], "payload_sha256": sha(body)})) != r["hash"]:
            return False, f"HASH_MISMATCH@{r['seq']}"
        if r.get("grants_authority") is not False:
            return False, f"AUTHORITY_GRANTED@{r['seq']}"
        prev = r["hash"]
    return True, prev


# --------------------------------------------------------------- receipt ----
def step_body(s):
    return canon({"mission_id": s["mission_id"], "index": s["index"], "kind": s["kind"],
                  "detail": s["detail"], "prev_hash": s["prev_hash"]})


def receipt_full(rec):
    h, steps, close = rec["header"], rec["steps"], rec["close"]
    pub = h["pubkey"]
    fails = []
    hb = {k: v for k, v in h.items() if k != "signature"}
    if not verify_sig(pub, h["signature"], canon(hb)):
        fails.append("HEADER_SIGNATURE_INVALID")
    if h.get("plan_hash") != sha(canon(h["plan_kinds"])):
        fails.append("PLAN_HASH")
    if h.get("plan_steps") != len(h["plan_kinds"]):
        fails.append("PLAN_COUNT")
    if len(steps) != h["plan_steps"]:
        fails.append("STEP_COUNT")
    if [s["kind"] for s in steps] != h["plan_kinds"]:
        fails.append("PLAN_SEQUENCE")
    if close.get("steps") != len(steps):
        fails.append("CLOSE_COUNT")
    prev = h["start_head"]
    for i, s in enumerate(steps):
        if s["index"] != i:
            fails.append(f"INDEX@{i}")
        if s["mission_id"] != h["mission_id"]:
            fails.append(f"MISSION@{i}")
        if s["prev_hash"] != prev:
            fails.append(f"CHAIN@{i}")
        if sha(step_body(s)) != s["step_hash"]:
            fails.append(f"HASH@{i}")
        if not verify_sig(pub, s["signature"], step_body(s)):
            fails.append(f"SIG@{i}")
        prev = s["step_hash"]
    if steps and close.get("head") != steps[-1]["step_hash"]:
        fails.append("HEAD")
    if close.get("merkle_root") != merkle([s["step_hash"] for s in steps]):
        fails.append("MERKLE")
    cb = {k: v for k, v in close.items() if k != "signature"}
    if not verify_sig(pub, close["signature"], canon(cb)):
        fails.append("CLOSE_SIG")
    return fails


def receipt_chain_only(rec):
    steps = rec["steps"]
    pub = rec["header"]["pubkey"]
    fails = []
    prev = steps[0]["prev_hash"] if steps else rec["header"].get("start_head")
    for i, s in enumerate(steps):
        if s["prev_hash"] != prev:
            fails.append(f"CHAIN@{i}")
        if not verify_sig(pub, s["signature"], step_body(s)):
            fails.append(f"SIG@{i}")
        prev = s["step_hash"]
    return fails


ATTACKS = ["truncate_tail", "drop_middle", "reorder_steps", "substitute_step_detail",
           "flip_vote_outcome", "change_action_commit", "replay_step_from_other_mission",
           "forge_step_signature", "alter_plan_length"]


def apply_attack(name, rec, other):
    import copy
    r = copy.deepcopy(rec)
    if name == "truncate_tail":
        r["steps"].pop()
    elif name == "drop_middle":
        r["steps"].pop(4)
    elif name == "reorder_steps":
        r["steps"][3:5] = list(reversed(r["steps"][3:5]))
    elif name == "substitute_step_detail":
        r["steps"][2]["detail"]["verified"] = 0
    elif name == "flip_vote_outcome":
        r["steps"][5]["detail"]["accepted"] = False
    elif name == "change_action_commit":
        r["steps"][6]["detail"]["L12"]["solved"] = 24
    elif name == "replay_step_from_other_mission":
        r["steps"][6] = copy.deepcopy(other["steps"][6])
    elif name == "forge_step_signature":
        r["steps"][1]["detail"]["verified"] = 999
        r["steps"][1]["signature"] = "00" * 64
    elif name == "alter_plan_length":
        r["header"]["plan_kinds"] = r["header"]["plan_kinds"][:-1]
        r["header"]["plan_steps"] -= 1
        r["header"]["plan_hash"] = sha(canon(r["header"]["plan_kinds"]))
    return r


def main():
    d = Path(sys.argv[1] if len(sys.argv) > 1 else ".")
    checks = []

    def ck(name, ok, detail=""):
        checks.append((name, bool(ok), detail))

    # ---- manifest --------------------------------------------------------
    man = json.loads((d / "GMR_MANIFEST.json").read_text())
    body = {k: v for k, v in man.items() if k != "signature"}
    pub = man["pubkey_ed25519"]
    ck("manifest signature", verify_sig(pub, man["signature"], canon(body)))
    listed = man["files"]
    missing = [f for f in listed if not (d / f).exists()]
    ck("declared files present", not missing, str(missing[:3]))
    bad = [f for f, h in listed.items() if (d / f).exists() and sha((d / f).read_bytes()) != h]
    ck("file hashes", not bad, str(bad[:3]))
    ck("merkle root", merkle([sha((d / f).read_bytes()) for f in listed if (d / f).exists()])
       == man["merkle_root"], man["merkle_root"][:16])

    # ---- preregistration + salts ----------------------------------------
    pre = json.loads((d / "GMR_PREREGISTRATION.json").read_text())
    frz = json.loads((d / "GMR_PREREGISTRATION_FREEZE.json").read_text())
    ck("preregistration hash", sha((d / "GMR_PREREGISTRATION.json").read_bytes())
       == frz["preregistration_sha256"])
    salts = json.loads((d / "SALTS.json").read_text())
    ck("salt commitments", all(sha(v.encode()) == frz["salt_commitments"][k]
                              for k, v in salts.items()))
    ck("preregistered hypotheses", len(pre["hypotheses"]) == 7, str(len(pre["hypotheses"])))

    # ---- governed memory -------------------------------------------------
    mem_ok = {}
    for s in ("salt1", "salt2"):
        exp = json.loads((d / f"GMR_MEMORY_{s}.json").read_text())
        ok, info = memory_ok(exp)
        mem_ok[s] = ok
        ck(f"{s} memory rows verify", ok, info if not ok else f"{len(exp['rows'])} rows")
        ck(f"{s} memory head", exp["head"] == info)

    # ---- run report ------------------------------------------------------
    rep = json.loads((d / "GMR_RUN_REPORT.json").read_text())
    ck("no model calls", rep["design"]["model_calls"] == 0)
    ck("arms present", set(rep["arms"]) == {"FULL", "ISOLATED", "UNVERIFIED", "FROZEN"})

    rec_ok, atk_ok, chain_miss = {}, {}, {}
    for s in ("salt1", "salt2"):
        rec = rep["arms"]["FULL"][s]["receipt"]
        other = rep["arms"]["FULL"]["salt2" if s == "salt1" else "salt1"]["receipt"]
        fails = receipt_full(rec)
        rec_ok[s] = not fails
        ck(f"{s} receipt verifies", not fails, ",".join(fails[:3]))
        ck(f"{s} receipt pinned head", rec["close"]["head"] == rec["steps"][-1]["step_hash"])
        ck(f"{s} receipt plan length", len(rec["steps"]) == rec["header"]["plan_steps"] == 10)
        full_rej, chain_rej = {}, {}
        for name in ATTACKS:
            t = apply_attack(name, rec, other)
            full_rej[name] = bool(receipt_full(t))
            chain_rej[name] = bool(receipt_chain_only(t))
        ck(f"{s} full verifier rejects all 9", all(full_rej.values()),
           str([k for k, v in full_rej.items() if not v]))
        chain_miss[s] = sorted(k for k, v in chain_rej.items() if not v)
        ck(f"{s} chain-only misses exactly the tail and the plan",
           chain_miss[s] == ["alter_plan_length", "truncate_tail"], str(chain_miss[s]))
        ck(f"{s} attack table matches report",
           all(c["full_rejected"] == full_rej[c["attack"]] and
               c["chain_only_rejected"] == chain_rej[c["attack"]] for c in rep["attacks"][s]))

    # ---- ladder recomputed from the task rows ----------------------------
    ladder = {}
    for s in ("salt1", "salt2"):
        ladder[s] = {}
        for L in ("L4", "L8", "L12"):
            ladder[s][L] = []
            for g in range(3):
                cap = rep["arms"]["FULL"][s]["gens"][g]["capability"][L]
                ladder[s][L].append(sum(1 for r in cap["rows"] if r["solved"]))
                if cap["solved"] != ladder[s][L][-1]:
                    ck(f"{s} g{g} {L} solved count", False)
    ck("ladder rows match", all(
        ladder[s][L][g] == rep["arms"]["FULL"][s]["gens"][g]["capability"][L]["solved"]
        for s in ladder for L in ladder[s] for g in range(3)))
    ck("ladder shape", all(ladder[s][L] == [24, 24, 24] if L == "L4" else
                           (ladder[s][L] == [0, 24, 24] if L == "L8" else [0, 0, 24])
                           for s in ladder for L in ladder[s]),
       json.dumps(ladder))

    # ---- hypotheses ------------------------------------------------------
    def final(s, arm, L):
        return rep["arms"][arm][s]["final_capability"][L]

    h1 = all(ladder[s]["L12"][2] - ladder[s]["L12"][0] >= 0.6 * 24 and
             all(ladder[s][L][i] <= ladder[s][L][i + 1] for L in ladder[s] for i in range(2))
             for s in ladder)
    ck("H1 capability ladder", h1 == (rep["hypotheses"]["H1_capability_ladder"]["verdict"] == "SUPPORTED"))
    h2 = all(rec_ok.values()) and all(sum(1 for c in rep["attacks"][s] if c["full_rejected"]) == 9
                                     for s in rec_ok)
    ck("H2 receipt completeness", h2 == (rep["hypotheses"]["H2_receipt_completeness"]["verdict"] == "SUPPORTED"))
    h3 = all(chain_miss[s] == ["alter_plan_length", "truncate_tail"] for s in chain_miss)
    ck("H3 chain-only insufficiency", h3 == (rep["hypotheses"]["H3_chain_only_insufficiency"]["verdict"] == "SUPPORTED"))
    h4 = (all(rep["arms"]["UNVERIFIED"][s]["memory"]["false_admits"] >= 1 for s in ladder)
          and all(final(s, "FULL", "L12") - final(s, "UNVERIFIED", "L12") >= 1 for s in ladder)
          and all(final(s, "FULL", "L12") == 24 for s in ladder)
          and all(final(s, "FROZEN", "L12") == 0 for s in ladder)
          and all(final(s, "ISOLATED", "L12") < final(s, "FULL", "L12") for s in ladder))
    ck("H4 verified admission load-bearing", h4 == (rep["hypotheses"]["H4_verified_admission_load_bearing"]["verdict"] == "SUPPORTED"))
    gov = rep["hypotheses"]["H5_governance"]["detail"]
    h5 = all(v["chain_ok"] and v["authority_refused"] == "REFUSED" and v["cross_tenant_read"] == 0
             and v["cross_tenant_write_refused"] and v["nonce_replay_refused"]
             and v["unanimous_three_voter_promotions"] and v["false_admits"] == 0 for v in gov.values())
    ck("H5 governance", h5 == (rep["hypotheses"]["H5_governance"]["verdict"] == "SUPPORTED"))
    ck("H5 memory chains re-verified", all(mem_ok.values()))
    h6 = all(rep["hypotheses"][k]["verdict"] == "SUPPORTED" for k in
             ("H1_capability_ladder", "H2_receipt_completeness", "H3_chain_only_insufficiency",
              "H4_verified_admission_load_bearing", "H5_governance"))
    ck("H6 replication", h6 == (rep["hypotheses"]["H6_replication"]["verdict"] == "SUPPORTED"))
    expect = "GOVERNED_MISSION_RECEIPT_SUPPORTED" if h6 and h1 and h2 and h3 and h4 and h5 else "NOT_SUPPORTED"
    ck("verdict matches the hypotheses", rep["verdict"] == expect, rep["verdict"])

    # ---- cost + seal -----------------------------------------------------
    for s in ("salt1", "salt2"):
        c = rep["costs"][s]
        ck(f"{s} cost arithmetic", abs(c["ratio"] - round(c["receipt_checks"] / c["reexecution_ops"], 6)) < 1e-9)
        ck(f"{s} receipt is far cheaper than re-execution", c["ratio"] < 0.05, str(c["ratio"]))
    sp = d / "GMR_OMEGA_SEAL.json"
    if sp.exists():
        seal = json.loads(sp.read_text())
        ck("omega seal bound", seal.get("merkle_root") == man["merkle_root"] and seal.get("verdict") == "ALLOWED",
           seal.get("seal_label", "missing"))
    else:
        ck("omega seal not yet issued (pre-seal copy)", True, "pre-seal")
    ck("external review recorded", rep.get("limits") and "NOT OBTAINED" in " ".join(rep["limits"]))

    fails = [n for n, ok, _ in checks if not ok]
    for n, ok, detail in checks:
        print(("PASS " if ok else "FAIL ") + n + (f"  [{detail}]" if detail and not ok else ""))
    print(f"{len(checks) - len(fails)}/{len(checks)} checks passed")
    return 0 if not fails else 1


if __name__ == "__main__":
    sys.exit(main())
