#!/usr/bin/env python3
"""E25 clean-room control-loop verifier. ZERO CAIN imports.

    python3 verifier.py <E25_CONTROL_LOOP_PROOF.json>

Independently recomputes the control-loop certificate hash, the outcome hash and the policy-history
hash, re-checks delegation attenuation, and confirms no invariant failures and that the observed
outcome is an OBSERVED-layer fact (not predicted/simulated). Exit 0 = verified.
"""
from __future__ import annotations

import hashlib
import json
import sys


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


def sha(d) -> str:
    return hashlib.sha256(canon(d)).hexdigest()


def verify(proof: dict) -> list:
    problems = []
    cert = proof.get("certificate", {})
    if sha(cert) != proof.get("certificate_hash"):
        problems.append("control-loop certificate hash mismatch")
    if cert.get("observed_outcome") is None:
        problems.append("certificate has no observed outcome")

    outcome = proof.get("outcome", {})
    if outcome and sha(outcome) != proof.get("outcome_hash"):
        problems.append("execution outcome hash mismatch")
    if outcome.get("observed_layer") not in (None, "OBSERVED"):
        problems.append("observed outcome is not an OBSERVED-layer fact")

    pol = proof.get("policy_history", {})
    if pol:
        expected = sha({"policy_id": pol.get("policy_id"), "version": pol.get("version"),
                        "history": pol.get("history"), "evidence": pol.get("evidence")})
        if expected != pol.get("history_hash"):
            problems.append("policy history hash mismatch")

    deleg = proof.get("delegation", {})
    if deleg:
        parent, child = deleg.get("parent", {}), deleg.get("child", {})
        if child and parent:
            if not set(child.get("capabilities", [])) <= set(parent.get("capabilities", [])):
                problems.append("delegation child capabilities exceed parent")
            if child.get("expires_at", 0) > parent.get("expires_at", 0):
                problems.append("delegation child expiration exceeds parent")

    inv = proof.get("invariants", {})
    if inv and inv.get("passed") != inv.get("total"):
        problems.append("invariant failures present")

    if proof.get("reassessment", {}).get("grants_authority") is not False:
        problems.append("reassessment must not grant authority")
    return problems


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


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