#!/usr/bin/env python3
"""E23 clean-room Frontier proof verifier. ZERO CAIN imports.

    python3 verifier.py <E23_FRONTIER_PROOF.json>

Independently verifies: authority conservation across the product chain, governance lineage
integrity, the replay envelope's logical hash, and the signed execution certificate.
Exit 0 = verified, 1 = failure. Verifies integrity/structure, 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


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)).hexdigest()


def _subset(out, inp) -> bool:
    return set(out) <= set(inp)


def verify(proof: dict) -> list:
    problems = []

    # 1. authority conservation
    for d in proof.get("authority_deltas", []):
        ain, aout = d["authority_in"], d["authority_out"]
        for dim in ("capabilities", "resources", "products"):
            if not _subset(aout.get(dim, []), ain.get(dim, [])):
                problems.append(f"{d['to_product']}: authority expanded in {dim}")
        if aout.get("principal") != ain.get("principal"):
            problems.append(f"{d['to_product']}: principal changed")
        if aout.get("tenant") != ain.get("tenant"):
            problems.append(f"{d['to_product']}: tenant changed")
        if aout.get("autonomy_level", 0) > ain.get("autonomy_level", 0):
            problems.append(f"{d['to_product']}: autonomy expanded")

    # 2. lineage integrity
    lineage = proof.get("lineage", {})
    nodes = lineage.get("nodes", [])
    ids = {n["node_id"] for n in nodes}
    for n in nodes:
        if n.get("parent_id") and n["parent_id"] not in ids:
            problems.append(f"lineage {n['node_id']}: missing predecessor {n['parent_id']}")
        if n.get("revoked") or n.get("stale"):
            problems.append(f"lineage {n['node_id']}: revoked/stale reference")
    tenants = {n.get("tenant") for n in nodes if n.get("tenant")}
    if len(tenants) > 1:
        problems.append(f"cross-tenant lineage: {sorted(tenants)}")
    kinds = {n.get("kind") for n in nodes}
    for required in ("AGENT", "AUTHORIZATION", "PERMIT", "COMMIT", "EXECUTION", "CERTIFICATE", "EVIDENCE", "STATE_UPDATE"):
        if required not in kinds:
            problems.append(f"lineage missing kind: {required}")

    # 3. replay envelope logical hash
    env = proof.get("replay_envelope", {})
    if env:
        expected = sha({"seed": env.get("deterministic_seed"), "request": env.get("logical_request"),
                        "identity": env.get("identity"), "policy": env.get("policy"),
                        "state_root": env.get("state_root"), "configuration_digest": env.get("configuration_digest"),
                        "software_revision": env.get("software_revision")})
        if expected != env.get("logical_hash"):
            problems.append("replay envelope logical hash mismatch")

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

    if not proof.get("final_root"):
        problems.append("missing final state root")
    return problems


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


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