#!/usr/bin/env python3
"""E21 clean-room state verifier (spec §28). ZERO CAIN imports.

    DON'T TRUST CAIN-42. VERIFY CAIN-42.

Given an E21 state-proof JSON (E21_STATE_PROOF.json), this independently recomputes the state-root
hierarchy, transition hash, witness hash and quorum-certificate signing digest, and verifies the
Ed25519 signatures — using its own re-implementation of the canonical maths.

    python3 state_verifier.py <E21_STATE_PROOF.json>

Exit 0 = verified, 1 = failure. Verifies integrity/provenance, not truth of the underlying facts.
"""
from __future__ import annotations

import base64
import hashlib
import json
import sys

try:
    from cryptography.exceptions import InvalidSignature
    from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
except Exception:  # pragma: no cover
    Ed25519PublicKey = None

ROOT_NAMES = ("governance", "identity", "authority", "policy", "agent", "delegation", "temporal",
              "epistemic", "risk", "consequence", "evidence", "execution", "federation", "frontier20")
_DOMAIN = "CainE21.state-root.v1:"
_CERT_DOMAIN = "CainE21.quorum-cert.v1"
_NODE = b"\x01"


def canon(data) -> bytes:
    return json.dumps(data, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8")


def sha(data) -> str:
    return hashlib.sha256(canon(data) if not isinstance(data, (bytes, bytearray)) else bytes(data)).hexdigest()


def leaf_hash(name, root) -> str:
    return sha({"domain": _DOMAIN, "name": name, "root": root})


def global_root(roots: dict) -> str:
    level = [bytes.fromhex(leaf_hash(n, roots.get(n))) for n in ROOT_NAMES]
    if not level:
        return sha(b"")
    while len(level) > 1:
        nxt = []
        for i in range(0, len(level), 2):
            left = level[i]
            right = level[i + 1] if i + 1 < len(level) else left
            nxt.append(hashlib.sha256(_NODE + left + right).digest())
        level = nxt
    return level[0].hex()


def transition_hash(transition: dict) -> str:
    body = {k: v for k, v in transition.items() if k != "quorum_reference"}
    return sha(body)


def witness_hash(witness: dict) -> str:
    return sha(witness)


def cert_signing_digest(cert: dict) -> str:
    return sha({
        "domain": _CERT_DOMAIN, "transition_id": cert["transition_id"], "state_root": cert["state_root"],
        "parent_root": cert["parent_root"], "epoch": cert["epoch"], "view": cert["view"],
        "sequence": cert["sequence"], "invariant_set_version": cert["invariant_set_version"],
        "witness_hash": cert["witness_hash"], "transition_hash": cert["transition_hash"],
    })


def verify(proof: dict) -> list:
    problems = []
    roots = proof["state_roots"]["roots"]
    if global_root(roots) != proof["state_roots"]["global_root"]:
        problems.append("global_state_root recomputation mismatch")

    th = transition_hash(proof["transition"])
    if th != proof["transition_hash"]:
        problems.append("transition_hash mismatch")

    wh = witness_hash(proof["witness"])
    if wh != proof["witness_hash"]:
        problems.append("witness_hash mismatch")

    cert = proof["certificate"]
    digest = cert_signing_digest(cert)
    if digest != cert.get("signing_digest"):
        problems.append("certificate signing_digest mismatch")
    if cert.get("transition_hash") != th:
        problems.append("certificate does not commit to the transition hash")

    threshold = cert["quorum_threshold"]
    valid = 0
    for vid, sig in cert["signatures"].items():
        pub = proof["public_keys"].get(vid)
        if pub is None:
            problems.append(f"no public key for {vid}")
            continue
        if Ed25519PublicKey is None:
            problems.append("cryptography unavailable")
            break
        try:
            Ed25519PublicKey.from_public_bytes(base64.b64decode(pub)).verify(
                base64.b64decode(sig), canon(digest))
            valid += 1
        except (InvalidSignature, ValueError):
            problems.append(f"invalid signature from {vid}")
    if valid < threshold:
        problems.append(f"valid signers {valid} < threshold {threshold}")

    history = proof["replay"]["root_history"]
    if history and history[-1] != proof["replay"]["final_root"]:
        problems.append("replay final root not at end of history")
    return problems


def main(argv: list) -> int:
    if len(argv) < 2:
        print("usage: state_verifier.py <E21_STATE_PROOF.json>", file=sys.stderr)
        return 2
    proof = json.load(open(argv[1], encoding="utf-8"))
    problems = verify(proof)
    if problems:
        print("STATE PROOF FAILED:")
        for p in problems:
            print("  -", p)
        return 1
    print("STATE PROOF VERIFIED (independent recomputation)")
    return 0


if __name__ == "__main__":
    raise SystemExit(main(sys.argv))
