#!/usr/bin/env python3
"""E22 clean-room execution verifier. ZERO CAIN imports.

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

    python3 verifier.py <E22_EXECUTION_PROOF.json>

Independently recomputes: the authorization↔state binding hash, the signed execution certificate,
and the composition chain (each step's output root, and the chain continuity from the initial root
to the final root). Exit 0 = verified, 1 = failure.
"""
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


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 verify(proof: dict) -> list:
    problems = []

    binding = proof.get("binding", {})
    if sha(binding) != proof.get("binding_hash"):
        problems.append("authorization-state binding hash mismatch")
    if binding.get("state_root") != proof.get("current_state_root"):
        problems.append("binding state root is not the current committed state (stale/rolled back)")

    env = proof.get("execution_certificate", {})
    body = env.get("certificate")
    if body is None:
        problems.append("execution certificate missing")
    else:
        if sha(body) != env.get("payload_hash"):
            problems.append("execution certificate payload hash mismatch")
        if Ed25519PublicKey is not None and env.get("signature_b64"):
            try:
                Ed25519PublicKey.from_public_bytes(base64.b64decode(env["public_key_b64"])).verify(
                    base64.b64decode(env["signature_b64"]), canon(body))
            except (InvalidSignature, ValueError, KeyError):
                problems.append("execution certificate signature invalid")
        # bind execution to authorization + state
        if body.get("state_root") != binding.get("state_root"):
            problems.append("execution certificate state root != binding state root")
        if body.get("authorization") != binding.get("authorization_id"):
            problems.append("execution certificate authorization != binding authorization")

    comp = proof.get("composition_certificate", {})
    if comp:
        if sha(comp) != proof.get("composition_certificate_hash"):
            problems.append("composition certificate hash mismatch")
        chain_root = sha({"composition_id": comp.get("composition_id"),
                          "graph": comp.get("product_graph"),
                          "roots": [comp.get("initial_state_root"), *comp.get("intermediate_roots", []),
                                    comp.get("final_state_root")]})
        if chain_root != proof.get("composition_chain_root"):
            problems.append("composition chain root mismatch")
        prev = comp.get("initial_state_root")
        for rec in proof.get("composition_steps", []):
            if rec.get("input_root") != prev:
                problems.append(f"composition step {rec.get('name')} input root breaks the chain")
            expected_out = sha({"product": rec.get("name"), "in": rec.get("input_root"),
                                "out": rec.get("result_hash")})
            if expected_out != rec.get("output_root"):
                problems.append(f"composition step {rec.get('name')} output root not reproducible")
            prev = rec.get("output_root")
        if proof.get("composition_steps") and prev != comp.get("final_state_root"):
            problems.append("composition final root is not the last step output")
    return problems


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


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