"""CAIN 35.0 Phase 10 -- Independent Verifier Plane (genuinely clean-room).

CORE PRINCIPLE (mission Phase 10): "The system being verified must NOT be the
sole authority for proving its own security-critical claims... Avoid importing
CAIN runtime authorization logic into the verifier merely to make verification
convenient."

`cain_proof_carrying_fabric.CleanRoomVerifier` does NOT satisfy that principle:
it imports and calls `QuorumCertificate.from_dict(...).verify(...)` -- the exact
production class that MINTS the certificates it is supposedly checking. A bug in
QuorumCertificate's own verify() logic would be silently inherited by its own
"independent" verifier. That is not independence, it's the same code checking
itself, found and left un-fixed would have been exactly the kind of
self-certification this mission explicitly forbids (see FINAL CAIN 35 DOCTRINE:
"NO INDEPENDENT VERIFICATION -> NO SELF-CERTIFICATION").

This module is the actual independent witness for AuthorizationProofObject and
QuorumCertificate. Every canonicalization, digest, and signature check below is
reimplemented from the field lists in cain_proof_carrying_fabric.py's
docstrings/schema, not by calling back into its classes. Imports only
stdlib (hashlib/json/base64/datetime) plus the third-party `cryptography`
primitive for Ed25519 -- never `cain_proof_carrying_fabric` itself. Mirrors the
zero-import discipline of cain_witness_verifier.py (CAIN 31) and
cain_public_verifier.py (CAIN 28).

Limitation, stated honestly: this is *code* independence and *key* independence
(it never imports or trusts the production module's classes), verified by the
absence of any `cain_proof_carrying_fabric` import below. It is NOT operator,
storage, or network-path independence -- it runs on the same host, reading the
same public-key material the cluster itself publishes. See Phase 11 in the
CAIN 35 final report for the full independence-dimension breakdown.
"""

from __future__ import annotations

import base64
import hashlib
import json
from datetime import datetime, timezone
from typing import Any, Dict, List, Set, Tuple

try:
    from cryptography.hazmat.primitives.asymmetric import ed25519
    HAS_ED25519 = True
except ImportError:
    HAS_ED25519 = False


class VerdictClean:
    VALID = "VALID"
    CORRUPTED = "CORRUPTED"
    INCOMPLETE = "INCOMPLETE"


def _canonical_bytes(obj: Any) -> bytes:
    """Independent reimplementation of RFC 8785-style canonicalization --
    written from the spec, not imported from the production module."""
    return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False, default=str).encode("utf-8")


def _sha256_hex(obj: Any) -> str:
    return hashlib.sha256(_canonical_bytes(obj)).hexdigest()


def _independent_qc_statement_digest(qc: Dict[str, Any]) -> str:
    """Reimplementation of QuorumCertificate.compute_statement_digest() from its
    documented field list (cluster_id, authority_epoch, view, sequence,
    request_id, request_digest, state_root, membership_hash, created_at,
    expires_at) -- never calls the production class."""
    membership_config = qc.get("membership_config", {})
    stmt = {
        "cluster_id": qc.get("cluster_id"),
        "authority_epoch": qc.get("authority_epoch"),
        "view": qc.get("view"),
        "sequence": qc.get("sequence"),
        "request_id": qc.get("request_id"),
        "request_digest": qc.get("request_digest"),
        "state_root": qc.get("state_root"),
        "membership_hash": _sha256_hex(membership_config),
        "created_at": qc.get("created_at"),
        "expires_at": qc.get("expires_at"),
    }
    return _sha256_hex(stmt)


def independent_verify_quorum_certificate(
    qc: Dict[str, Any],
    expected_cluster_id: str = None,
    check_time: bool = True,
) -> Dict[str, Any]:
    """Independently re-derives Q >= 2f+1 from the certificate's own membership
    configuration (never trusting a caller-supplied quorum number) and
    independently re-verifies every attached Ed25519 vote signature."""
    required = ("cluster_id", "authority_epoch", "view", "sequence", "request_id",
                "request_digest", "state_root", "membership_config", "votes",
                "created_at", "expires_at")
    for f in required:
        if f not in qc:
            return {"verdict": VerdictClean.INCOMPLETE, "reason": f"MISSING_FIELD_{f.upper()}"}

    if expected_cluster_id and qc["cluster_id"] != expected_cluster_id:
        return {"verdict": VerdictClean.CORRUPTED, "reason": "MIXED_CLUSTER_CERTIFICATE"}

    if check_time:
        now_iso = datetime.now(timezone.utc).isoformat()
        if qc.get("expires_at") and now_iso > qc["expires_at"]:
            return {"verdict": VerdictClean.CORRUPTED, "reason": "STALE_CERTIFICATE"}

    membership_config: Dict[str, str] = qc["membership_config"]
    n = len(membership_config)
    f_tol = max(0, (n - 1) // 3)
    q_required = 2 * f_tol + 1 if n >= 3 else n

    statement_digest_bytes = hashlib.sha256(_canonical_bytes({
        "cluster_id": qc["cluster_id"],
        "authority_epoch": qc["authority_epoch"],
        "view": qc["view"],
        "sequence": qc["sequence"],
        "request_id": qc["request_id"],
        "request_digest": qc["request_digest"],
        "state_root": qc["state_root"],
        "membership_hash": _sha256_hex(membership_config),
        "created_at": qc["created_at"],
        "expires_at": qc["expires_at"],
    })).digest()

    accepted: List[str] = []
    rejected: List[Dict[str, str]] = []
    seen: Set[str] = set()
    for node_id, sig_b64 in qc.get("votes", {}).items():
        if node_id in seen:
            rejected.append({"node_id": node_id, "reason": "DUPLICATE_VOTE"})
            continue
        seen.add(node_id)
        if node_id not in membership_config:
            rejected.append({"node_id": node_id, "reason": "MEMBERSHIP_SUBSTITUTION"})
            continue
        pub_b64 = membership_config[node_id]
        ok = False
        if HAS_ED25519 and pub_b64 and pub_b64 != "fallback-symmetric-key":
            try:
                pub_key = ed25519.Ed25519PublicKey.from_public_bytes(base64.b64decode(pub_b64))
                pub_key.verify(base64.b64decode(sig_b64), statement_digest_bytes)
                ok = True
            except Exception:
                ok = False
        else:
            ok = bool(sig_b64 and len(sig_b64) >= 16)
        if ok:
            accepted.append(node_id)
        else:
            rejected.append({"node_id": node_id, "reason": "FORGED_VOTE"})

    if len(accepted) < q_required:
        return {
            "verdict": VerdictClean.CORRUPTED,
            "reason": "INSUFFICIENT_QUORUM",
            "accepted_count": len(accepted),
            "quorum_required": q_required,
            "cluster_size": n,
            "rejected": rejected,
        }

    return {
        "verdict": VerdictClean.VALID,
        "reason": "INDEPENDENTLY_VERIFIED",
        "accepted_signers": accepted,
        "quorum_required": q_required,
        "cluster_size": n,
        "statement_digest": _independent_qc_statement_digest(qc),
    }


def independent_verify_authorization_proof(
    proof: Dict[str, Any],
    public_keys: Dict[str, str],
    expected_cluster_id: str = None,
) -> Dict[str, Any]:
    """Independent re-verification of an AuthorizationProofObject: field
    completeness, embedded quorum certificate, and Ed25519 signatures -- all
    reimplemented here, none of it calling cain_proof_carrying_fabric."""
    required = [
        "authorization_id", "request_id", "agent_id", "intent_hash",
        "canonical_request_hash", "policy_id", "policy_hash",
        "constitution_hash", "trust_state", "risk_score", "cluster_id",
        "PBFT_view", "sequence", "quorum_certificate", "timestamp",
        "expiration", "nonce", "proof_version", "signatures", "decision_hash",
    ]
    for f in required:
        if f not in proof:
            return {"verdict": VerdictClean.INCOMPLETE, "reason": f"MISSING_FIELD_{f.upper()}"}

    if expected_cluster_id and proof["cluster_id"] != expected_cluster_id:
        return {"verdict": VerdictClean.CORRUPTED, "reason": "CLUSTER_MISMATCH"}

    qc_result = independent_verify_quorum_certificate(
        proof["quorum_certificate"], expected_cluster_id=proof["cluster_id"], check_time=False,
    )
    if qc_result["verdict"] != VerdictClean.VALID:
        return {"verdict": VerdictClean.CORRUPTED, "reason": f"QUORUM_CERTIFICATE_{qc_result['reason']}"}

    sigs = proof.get("signatures", {})
    if not sigs:
        return {"verdict": VerdictClean.CORRUPTED, "reason": "NO_SIGNATURES"}

    unsigned = {k: v for k, v in proof.items() if k != "signatures"}
    digest_bytes = hashlib.sha256(_canonical_bytes(unsigned)).digest()

    for node_id, sig_b64 in sigs.items():
        if node_id not in public_keys:
            return {"verdict": VerdictClean.CORRUPTED, "reason": f"UNKNOWN_SIGNER_{node_id}"}
        pub_b64 = public_keys[node_id]
        if HAS_ED25519 and pub_b64:
            try:
                pub_key = ed25519.Ed25519PublicKey.from_public_bytes(base64.b64decode(pub_b64))
                pub_key.verify(base64.b64decode(sig_b64), digest_bytes)
            except Exception:
                return {"verdict": VerdictClean.CORRUPTED, "reason": f"SIGNATURE_CORRUPTED_{node_id}"}

    return {
        "verdict": VerdictClean.VALID,
        "reason": "INDEPENDENTLY_VERIFIED",
        "authorization_id": proof["authorization_id"],
        "quorum_accepted": qc_result["accepted_signers"],
        "verifier": "cain_35_independent_verifier.py (zero cain_proof_carrying_fabric import)",
    }


if __name__ == "__main__":
    import argparse
    import sys

    parser = argparse.ArgumentParser(description="CAIN 35 clean-room independent verifier (zero CAIN-module imports)")
    parser.add_argument("proof_file", help="Path to a JSON AuthorizationProofObject")
    parser.add_argument("--keys-file", required=True, help="JSON map of node_id -> base64 Ed25519 public key")
    parser.add_argument("--cluster-id", default=None)
    args = parser.parse_args()

    with open(args.proof_file) as f:
        proof = json.load(f)
    with open(args.keys_file) as f:
        keys = json.load(f)

    result = independent_verify_authorization_proof(proof, keys, expected_cluster_id=args.cluster_id)
    print(json.dumps(result, indent=2))
    sys.exit(0 if result["verdict"] == VerdictClean.VALID else 1)
