#!/usr/bin/env python3
"""E330 standalone offline verifier (stdlib + cryptography; imports no CAIN code).

Checks the manifest signature, every file digest, the Merkle root, the preregistration hash, the
freeze ordering, the salt commitments, the external-review status, the 192-row record chain, the
attestation certificate decision rule, and recomputes every hypothesis and the verdict from the
raw rows. The engine source is withheld by the IP rule; the verifier validates the recorded
attestation certificates and the fail-closed decision rule, not the engine implementation.
"""
from __future__ import annotations

import hashlib
import json
import sys
from pathlib import Path

S = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
ENG = ("attest.py", "lab.py", "run.py")
EX = {"E330_MANIFEST.json", "E330_SIGNED_BODY.json", "E330_VERIFICATION_RESULTS.json", "MANIFEST.json",
      "MERKLE_ROOT.txt", "PUBLICATION.json", "E330_OMEGA_SEAL.json", "E330_TAMPER_RESULTS.json",
      "E330_ACCEPTANCE_REGISTRY.json"}
BENIGN = {"normal", "idle", "optional_rank_null", "slow_within_ttl"}
CHAIN_CLASSES = {"series_order", "series_dup", "dig_tamper", "prev_tamper", "head_tamper",
                 "truncation", "truncation_consistent", "extra_entry"}
CROSS_CLASSES = {"cross_height", "cross_evidence", "cross_seals", "cross_claims", "state_height_tamper"}
NULL_SCHEMA = {"null_mask", "schema"}


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


def sha(b):
    return hashlib.sha256(b).hexdigest()


def merkle(paths):
    leaves = sorted(sha(p.read_bytes()) for p in paths)
    if not leaves:
        return sha(b"")
    while len(leaves) > 1:
        if len(leaves) % 2:
            leaves.append(leaves[-1])
        leaves = [sha((leaves[i] + leaves[i + 1]).encode()) for i in range(0, len(leaves), 2)]
    return leaves[0]


def chain(rows):
    prev = "0" * 64
    out = []
    for r in rows:
        h = sha((prev + sha(canon(r))).encode())
        out.append({"i": len(out), "prev": prev, "hash": h})
        prev = h
    return out


def entry_dig(prev, e):
    payload = {"hb": e.get("hb"), "height": e.get("height"), "decisions": e.get("decisions"),
               "evidence": e.get("evidence"), "seals": e.get("seals"), "claims": e.get("claims")}
    return sha((prev + sha(canon(payload))).encode())


def state_digest(feed):
    payload = {k: feed.get(k) for k in ("schema", "generated_at", "heartbeat", "cluster", "metrics",
                                        "checkpoint", "seals", "claims", "chain_head", "chain_len",
                                        "sources_ok", "nulls")}
    return sha(canon(payload))


def feed_integrity(feed, sources, anchor, now, ttl):
    """Recompute the recorded feed's cryptographic integrity and cross-source equality."""
    bad = []
    series = feed.get("series") or []
    prev = "0" * 64
    for e in series:
        if e.get("prev") != prev or e.get("dig") != entry_dig(prev, e):
            bad.append("chain")
            break
        prev = e.get("dig")
    if feed.get("chain_head") != prev:
        bad.append("head")
    if feed.get("chain_len") != len(series):
        bad.append("len")
    hbs = [e.get("hb") for e in series]
    if not (all(isinstance(x, int) for x in hbs) and all(hbs[i] < hbs[i + 1] for i in range(len(hbs) - 1))):
        bad.append("order")
    if not series or feed.get("heartbeat") != series[-1].get("hb"):
        bad.append("beat")
    if feed.get("state_digest") != state_digest(feed):
        bad.append("digest")
    gen = feed.get("generated_at")
    if not isinstance(gen, (int, float)) or now - gen > ttl or gen - now > 5:
        bad.append("time")
    ahb = (anchor or {}).get("heartbeat")
    if ahb is not None and isinstance(feed.get("heartbeat"), int) and feed["heartbeat"] <= ahb:
        bad.append("monotonic")
    alen = (anchor or {}).get("chain_len")
    ahead = (anchor or {}).get("chain_head")
    if (alen is not None and len(series) < alen) or (ahead is not None and ahead not in {e.get("dig") for e in series}):
        bad.append("truncation")
    cross = [(feed.get("cluster") or {}).get("height"), ((sources or {}).get("cluster") or {}).get("height"),
             (feed.get("checkpoint") or {}).get("evidence_records"), ((sources or {}).get("checkpoint") or {}).get("tree_size"),
             (feed.get("seals") or {}).get("count"), ((sources or {}).get("seals") or {}).get("count"),
             (feed.get("claims") or {}).get("total"), ((sources or {}).get("claims") or {}).get("total")]
    if cross[0] != cross[1] or cross[2] != cross[3] or cross[4] != cross[5] or cross[6] != cross[7]:
        bad.append("cross")
    if (sources or {}).get("cluster") is None or (sources or {}).get("checkpoint") is None \
            or (sources or {}).get("seals") is None or (sources or {}).get("claims") is None:
        bad.append("null")
    return bad


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

    def ck(n, ok, d=""):
        c.append({"check": n, "ok": bool(ok), "detail": str(d)[:300]})

    man = json.loads((B / "E330_MANIFEST.json").read_text())
    ck("schema", man.get("schema") == "cain42.e330.manifest.v1")
    ck("status", man.get("status") == S)
    body = {k: v for k, v in man.items() if k != "signature"}
    try:
        from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(
            bytes.fromhex(man["signature"]), canon(body))
        ck("signature", True)
    except Exception as ex:
        ck("signature", False, ex)
    files = man.get("files", {})
    ck("files present", all((B / k).exists() for k in files))
    ck("file hashes", not [k for k, h in files.items() if (B / k).exists() and sha((B / k).read_bytes()) != h])
    ck("merkle", merkle(sorted(B / k for k in files if (B / k).exists())) == man.get("merkle_root"))
    present = {str(x.relative_to(B)) for x in B.rglob("*") if x.is_file() and "__pycache__" not in x.parts}
    ck("no unlisted file", not (present - set(files) - EX), sorted(present - set(files) - EX)[:5])
    ck("source withheld", not any((B / n).exists() for n in ENG))

    pre = json.loads((B / "E330_PREREGISTRATION.json").read_text())
    frz = json.loads((B / "E330_PREREGISTRATION_FREEZE.json").read_text())
    rep = json.loads((B / "E330_RUN_REPORT.json").read_text())
    rev = json.loads((B / "E330_SALT_REVEALED.json").read_text())
    ck("prereg hash", sha((B / "E330_PREREGISTRATION.json").read_bytes()) == frz["preregistration_sha256"])
    ck("freeze before run", frz["frozen_at"] <= rep["generated_at"])
    ck("salt commitments", all(sha(bytes.fromhex(rev["salts"][k])) == pre["salt_commitment_sha256"][k]
                               for k in rev["salts"]))
    ck("external not faked", json.loads((B / "E330_EXTERNAL_REVIEW_STATUS.json").read_text()).get("status") == "NOT_OBTAINED")
    ck("engine hashes", len(pre.get("engine_sha256", {})) == 3)

    rows = []
    for salt in ("primary", "replication"):
        rs = rep["sets"][salt]["rows"]
        rows += rs
        ck(f"{salt} rows", len(rs) == 96, len(rs))
        ck(f"{salt} scenarios", len({(r["scenario"], r["world"]) for r in rs}) == 96)
    ck("total rows", len(rows) == 192, len(rows))

    # the fail-closed decision rule must hold on every recorded certificate
    rule_bad = []
    for r in rows:
        checks = r.get("checks") or []
        failed = [x for x in checks if not x.get("ok")]
        reasons = r.get("reasons") or []
        accept = r.get("verdict") == "ACCEPT"
        if accept != (not failed) or accept != (not reasons):
            rule_bad.append((r.get("scenario"), r.get("world"), r.get("verdict"), len(failed), reasons))
    ck("decision rule", not rule_bad, rule_bad[:3])
    ck("typed reasons", all(isinstance(x, str) and x.isupper() for r in rows for x in (r.get("reasons") or [])))

    def fin(r):
        return feed_integrity(r.get("feed") or {}, r.get("sources") or {}, r.get("anchor") or {},
                              r.get("now"), r.get("ttl_s") or 120)

    benign_bad = [(r["scenario"], r["world"], fin(r)) for r in rows if r["scenario"] in BENIGN and fin(r)]
    ck("benign feed integrity", not benign_bad, benign_bad[:3])
    chain_not = [(r["scenario"], r["world"], fin(r)) for r in rows
                 if r["scenario"] in CHAIN_CLASSES and not ({"chain", "head", "len", "order", "truncation"} & set(fin(r)))]
    ck("chain rows tampered", not chain_not, chain_not[:3])
    cross_not = [(r["scenario"], r["world"], fin(r)) for r in rows
                 if r["scenario"] in CROSS_CLASSES and "cross" not in fin(r)]
    ck("cross rows diverge", not cross_not, cross_not[:3])
    null_not = [(r["scenario"], r["world"], fin(r)) for r in rows
                if r["scenario"] == "null_mask" and "null" not in fin(r)]
    ck("null row masks a null", not null_not, null_not[:3])

    benign = [r for r in rows if r["scenario"] in BENIGN]
    attacks = [r for r in rows if r["scenario"] not in BENIGN]
    bacc = sum(1 for r in benign if r["verdict"] == "ACCEPT")
    arej = sum(1 for r in attacks if r["verdict"] == "REJECT")
    rmatch = sum(1 for r in attacks if set(r.get("expected") or []) & set(r.get("reasons") or []))
    rate = rmatch / max(1, len(attacks))
    chain_rows = [r for r in attacks if r["scenario"] in CHAIN_CLASSES]
    cross_rows = [r for r in attacks if r["scenario"] in CROSS_CLASSES]
    null_rows = [r for r in attacks if r["scenario"] in NULL_SCHEMA]
    chain_ok = sum(1 for r in chain_rows if r["verdict"] == "REJECT")
    cross_ok = sum(1 for r in cross_rows if r["verdict"] == "REJECT")
    null_ok = sum(1 for r in null_rows if r["verdict"] == "REJECT")

    ps = rep["sets"]["primary"]["summary"]
    rs_ = rep["sets"]["replication"]["summary"]
    ts = rep["summary"]["all"]
    ck("summary benign", ts["benign"] == len(benign) and ts["benign_accept"] == bacc)
    ck("summary attacks", ts["attacks"] == len(attacks) and ts["attacks_rejected"] == arej)
    ck("summary reason", abs(ts["reason_rate"] - rate) < 1e-6)
    ck("summary classes", ts["chain_detected"] == chain_ok and ts["cross_detected"] == cross_ok
       and ts["null_schema_detected"] == null_ok)

    h1 = bacc == len(benign) and ts["false_alarms"] == 0
    h2 = arej == len(attacks)
    h3 = rate >= 0.95
    h4 = chain_ok == len(chain_rows)
    h5 = cross_ok == len(cross_rows)
    h6 = null_ok == len(null_rows) and ts["false_alarms"] == 0
    h7 = (rs_["benign_accept"] == rs_["benign"] and rs_["false_alarms"] == 0
          and rs_["attacks_rejected"] == rs_["attacks"])
    H = rep["hypotheses"]
    exp = {"H1_benign_accepted": h1, "H2_attacks_rejected": h2, "H3_typed_reason": h3,
           "H4_chain_classes": h4, "H5_cross_source_classes": h5, "H6_null_and_schema": h6,
           "H7_replication": h7}
    for k, ok in exp.items():
        ck(f"{k} verdict", H[k]["verdict"] == ("SUPPORTED" if ok else "NOT_SUPPORTED"))
    ck("H8 blocked", H["H8_external_review"]["verdict"] == "BLOCKED")
    verdict = "LIVE_STATE_ATTESTATION_SUPPORTED" if all(exp.values()) else "NOT_SUPPORTED"
    ck("verdict", verdict == rep["verdict"] == man.get("label"))
    f = rep["finding"]
    ck("finding consistent", f["benign_accept"] == f"{bacc}/{len(benign)}"
       and f["attacks_rejected"] == f"{arej}/{len(attacks)}"
       and f["reason_match"] == f"{rmatch}/{len(attacks)}"
       and f["chain_detected"] == f"{chain_ok}/{len(chain_rows)}"
       and f["cross_detected"] == f"{cross_ok}/{len(cross_rows)}"
       and f["null_schema_detected"] == f"{null_ok}/{len(null_rows)}")
    hl = man.get("headline", {})
    ck("manifest headline", hl.get("verdict") == verdict and hl.get("rows") == 192
       and hl.get("benign_accept") == bacc and hl.get("attacks_rejected") == arej
       and hl.get("reason_match") == rmatch)
    ch = chain(rows)
    cp = json.loads((B / "checkpoints/claim_chain.json").read_text())
    ck("chain count", cp["count"] == 192)
    ck("chain head", cp["head"] == ch[-1]["hash"])
    ck("chain mid", cp["mid"] == ch[len(ch) // 2]["hash"])
    ck("chain recompute", sha((ch[-2]["hash"] + sha(canon(rows[-1]))).encode()) == ch[-1]["hash"])
    ck("status line", S in (B / "E330_FINAL_REPORT.md").read_text())
    ck("limits present", len(rep.get("limits", [])) >= 5)
    ck("zero model calls", rep["resources"]["model_calls"] == 0)
    ck("no api spend", float(rep["resources"]["api_spend_usd"]) == 0.0)
    ck("no weights", rep["resources"]["weights_changed"] is False)

    passed = sum(1 for x in c if x["ok"])
    print(json.dumps({"schema": "cain42.e330.verify.v1", "checks": len(c), "passed": passed,
                      "failed": [x for x in c if not x["ok"]], "ok": passed == len(c)}, indent=1))
    return 0 if passed == len(c) else 1


if __name__ == "__main__":
    raise SystemExit(main())
