#!/usr/bin/env python3
"""E397-M standalone verifier: rebuilds records, grants, server modes and every client decision."""
from __future__ import annotations

import hashlib, json, sys
from pathlib import Path
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey

S = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
EX = {"E397-M_MANIFEST.json", "E397-M_SIGNED_BODY.json", "E397-M_VERIFICATION_RESULTS.json",
      "MANIFEST.json", "MERKLE_ROOT.txt", "PUBLICATION.json", "E397-M_OMEGA_SEAL.json", "E397-M_TAMPER_RESULTS.json"}
FIELDS = ("record_id", "status", "amount", "payload", "timestamp")
SCOPE = ("record_id", "status", "amount", "timestamp")
MODES = ("HONEST", "OVER_SERVE", "UNDER_SERVE", "WRONG_SUBJECT", "EXPIRED", "FORGED")
READER = "analyst-1"
RECORDS = 40


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) else b.encode()).hexdigest()
def key(name): return Ed25519PrivateKey.from_private_bytes(hashlib.sha256(name.encode()).digest())
def pub(k): return k.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw).hex()
def leaf(f, v): return sha(canon({"field": f, "value": v}))
def merkle(leaves):
    if not leaves: return sha(b"")
    lvl = list(leaves)
    while len(lvl) > 1:
        padded = lvl + ([lvl[-1]] if len(lvl) % 2 else [])
        lvl = [sha((padded[i] + padded[i + 1]).encode()) for i in range(0, len(padded), 2)]
    return lvl[0]
def proof_for(leaves, idx):
    lvl, pos, proof = list(leaves), idx, []
    while len(lvl) > 1:
        padded = lvl + ([lvl[-1]] if len(lvl) % 2 else [])
        proof.append({"side": "right" if pos % 2 == 0 else "left", "hash": padded[pos ^ 1]})
        lvl = [sha((padded[i] + padded[i + 1]).encode()) for i in range(0, len(padded), 2)]
        pos //= 2
    return proof
def root_from_proof(lf, proof):
    h = lf
    for st in proof:
        h = sha((h + st["hash"]).encode()) if st["side"] == "right" else sha((st["hash"] + h).encode())
    return h
AGENT, AUTH = key("e397m|agent"), key("e397m|authority")


def build(i):
    values = {"record_id": f"r-{i:03d}", "status": "VERIFIED" if i % 2 else "PENDING",
              "amount": 100 + i, "payload": f"SECRET-PAYLOAD-{i:03d}", "timestamp": f"2026-11-26T13:{i % 60:02d}:00Z"}
    leaves = [leaf(f, values[f]) for f in FIELDS]
    root = merkle(leaves)
    body = {"record_id": values["record_id"], "schema": list(FIELDS), "field_root": root}
    return {"values": values, "leaves": leaves, "root": root, "sig": AGENT.sign(canon(body)).hex(), "body": body}


def grant(not_after="2099-01-01T00:00:00Z", signer=AUTH, subject=READER):
    body = {"kind": "read_grant", "grant_id": f"g-{READER}", "subject": subject, "fields": list(SCOPE),
            "issued_at": "2026-11-26T00:00:00Z", "not_after": not_after}
    return {**body, "sig": signer.sign(canon(body)).hex(), "signer": "authority"}


def serve(rec, mode):
    fields = set(SCOPE)
    if mode == "OVER_SERVE": fields.add("payload")
    if mode == "UNDER_SERVE": fields.discard("amount")
    visible = {f: rec["values"][f] for f in FIELDS if f in fields}
    return {"record_id": rec["values"]["record_id"], "scope": "ANALYST", "field_root": rec["root"],
            "schema": list(FIELDS), "signature": rec["sig"], "body": rec["body"],
            "visible": visible, "proofs": {f: proof_for(rec["leaves"], FIELDS.index(f)) for f in visible}}


def client_accept(view, g, identity, at="2026-11-26T12:00:00Z"):
    body = {k: g[k] for k in g if k not in ("sig", "signer")}
    try:
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(pub(AUTH))).verify(bytes.fromhex(g["sig"]), canon(body))
    except Exception:
        return False, "GRANT_SIGNATURE_INVALID"
    if g["subject"] != identity: return False, "GRANT_SUBJECT_MISMATCH"
    if at > g["not_after"]: return False, "GRANT_EXPIRED"
    allowed = set(g["fields"])
    try:
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(pub(AGENT))).verify(bytes.fromhex(view["signature"]), canon(view["body"]))
    except Exception:
        return False, "RECORD_SIGNATURE_INVALID"
    if view["field_root"] != view["body"]["field_root"]: return False, "ROOT_MISMATCH"
    for f in view["visible"]:
        if f not in allowed: return False, "FIELD_NOT_IN_GRANT"
    if allowed - set(view["visible"]): return False, "MISSING_FIELD"
    for f, v in view["visible"].items():
        if root_from_proof(leaf(f, v), view["proofs"][f]) != view["field_root"]: return False, "PROOF_INVALID"
    if "payload" in view["visible"]: return False, "FIELD_NOT_IN_GRANT"
    return True, "ACCEPTED"


def main():
    d = Path(sys.argv[1] if len(sys.argv) > 1 else ".")
    checks = []
    def ck(n, c): checks.append((n, bool(c)))
    man = json.loads((d / "E397-M_MANIFEST.json").read_text())
    pre = json.loads((d / "E397-M_PREREGISTRATION.json").read_text())
    frz = json.loads((d / "E397-M_PREREGISTRATION_FREEZE.json").read_text())
    rep = json.loads((d / "E397-M_RUN_REPORT.json").read_text())
    salt = json.loads((d / "E397-M_SALT_REVEALED.json").read_text())
    acc = json.loads((d / "E397-M_ACCEPTANCE_REGISTRY.json").read_text())
    dev = json.loads((d / "E397-M_DEVIATIONS.json").read_text())
    ck("schema", man.get("schema") == "cain42.e397m.manifest.v1" and rep.get("evolution") == "E397-M")
    files = sorted(p for p in d.rglob("*") if p.is_file() and str(p.relative_to(d)) not in EX and "__pycache__" not in p.parts)
    ck("files", set(man["files"]) == {str(p.relative_to(d)) for p in files})
    ck("hashes", all(sha(p.read_bytes()) == man["files"][str(p.relative_to(d))] for p in files))
    def path_merkle(paths):
        leaves = sorted(sha(p.read_bytes()) for p in paths)
        if not leaves: return sha(b"")
        lvl = leaves
        while len(lvl) > 1:
            if len(lvl) % 2: lvl.append(lvl[-1])
            lvl = [sha((lvl[i] + lvl[i + 1]).encode()) for i in range(0, len(lvl), 2)]
        return lvl[0]
    ck("merkle", man["merkle_root"] == path_merkle(files))
    ck("merkle file", (d / "MERKLE_ROOT.txt").read_text().strip() == man["merkle_root"])
    pubk = Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"]))
    pubk.verify(bytes.fromhex(man["signature"]), canon(json.loads((d / "E397-M_SIGNED_BODY.json").read_text())))
    ck("signature", True)
    ck("freeze", sha((d / "E397-M_PREREGISTRATION.json").read_bytes()) == frz["preregistration_sha256"] == rep["preregistration_sha256"])
    ck("salts", all(sha(bytes.fromhex(v)) == pre["salt_commitment_sha256"][k] for k, v in salt["salts"].items()))
    ck("source withheld", not any(q.name in ("run.py", "verify.py") for q in d.rglob("*") if q.is_file()))
    rows = {(r["record"], r["mode"]): r for r in rep["views"]}
    ck("views", len(rows) == 240)
    acc_counts = {m: 0 for m in MODES}
    for i in range(1, RECORDS + 1):
        rec = build(i)
        for mode in MODES:
            g = grant()
            if mode == "WRONG_SUBJECT": g = grant(subject="analyst-2")
            if mode == "EXPIRED": g = grant(not_after="2026-01-01T00:00:00Z")
            if mode == "FORGED": g = grant(signer=key("e397m|attacker"))
            ok, reason = client_accept(serve(rec, mode), g, READER)
            acc_counts[mode] += 1 if ok else 0
            r = rows[(i, mode)]
            if r["accepted"] != ok or r["reason"] != reason:
                checks.append((f"view {i}/{mode}", False))
    H = {
        "H1_honest_accepted": {"verdict": "SUPPORTED" if acc_counts["HONEST"] == RECORDS else "NOT_SUPPORTED",
                               "detail": "the honest server's view is accepted and fully verified by the client"},
        "H2_over_serve_detected": {"verdict": "SUPPORTED" if acc_counts["OVER_SERVE"] == 0 else "NOT_SUPPORTED",
                                   "detail": "a view with a field outside the grant is rejected by the client even though the server sent it"},
        "H3_under_serve_detected": {"verdict": "SUPPORTED" if acc_counts["UNDER_SERVE"] == 0 else "NOT_SUPPORTED",
                                    "detail": "a view missing a granted field is rejected as incomplete"},
        "H4_grant_checks": {"verdict": "SUPPORTED" if acc_counts["WRONG_SUBJECT"] == acc_counts["EXPIRED"] == acc_counts["FORGED"] == 0 else "NOT_SUPPORTED",
                            "detail": "wrong-subject, expired and forged grants are refused before any field is trusted"},
        "H5_no_leak_accepted": {"verdict": "SUPPORTED" if sum(1 for r in rows.values() if r["accepted"] and r["leaked_in_served_view"]) == 0 else "NOT_SUPPORTED",
                                "detail": "no accepted view contains the payload, although the malicious server served it"},
        "H6_external_review": {"verdict": "BLOCKED", "detail": "external review NOT OBTAINED"},
    }
    verdict = ("CLIENT_ENFORCED_SCOPE_SUPPORTED" if all(H[k]["verdict"] == "SUPPORTED" for k in H if k != "H6_external_review") else "NOT_SUPPORTED")
    ck("verdict", verdict == rep["verdict"] and all(H[k]["verdict"] == rep["hypotheses"][k]["verdict"] for k in H))
    ck("headline", rep["finding"]["headline"]["honest_accepted"] == acc_counts["HONEST"]
       and rep["finding"]["headline"]["served_payload_views"] == 40
       and rep["finding"]["headline"]["accepted_payload_views"] == 0)
    ch = [json.loads(l) for l in (d / "checkpoints/views_chain.jsonl").read_text().splitlines()]
    hh = sha(("0" * 64 + sha(canon(rep["probe"]))).encode())
    ck("chain", len(ch) == 1 and ch[0]["prev"] == "0" * 64 and ch[0]["hash"] == hh == rep["checkpoint"]["head"])
    cp = json.loads((d / "checkpoints/views_chain.json").read_text())
    ck("chain file", cp["count"] == 1 and cp["head"] == hh)
    ck("finding", rep["finding"]["headline"]["views"] == 240 and rep["finding"]["law"].startswith("a scope is a control"))
    ck("report verdict", f"**Preregistered verdict: {rep['verdict']}.**" in (d / "E397-M_FINAL_REPORT.md").read_text())
    ck("public summary", rep["verdict"] in (d / "E397-M_PUBLIC_SUMMARY.md").read_text())
    ck("acceptance", acc["verdict"] == rep["verdict"])
    ck("deviations", isinstance(dev.get("deviations"), list))
    ck("resources", rep["resources"]["model_calls"] == 0)
    bad = [n for n, ok in checks if not ok]
    for n, ok in checks: print(("PASS " if ok else "FAIL ") + n)
    print(f"{len(checks)-len(bad)}/{len(checks)} checks passed")
    return 0 if not bad else 1


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