"""CAIN 41.0 Phase 7 -- Independent Verifier 4.0 (zero-import from production).

Rules this module follows, per the CAIN 41 mission:
- NO IMPORT of cain_universal_proof_41.py (the production composition/signing
  module) or any other production CAIN engine module.
- NO TRUST in a CAIN API response, database row, or the production module's
  own claim that a proof is valid -- every check here is independently
  recomputed from raw evidence.
- Composes with (imports) cain_37_independent_verifier.py, itself already a
  zero-import verifier (AST-parse-verified since CAIN 35/37), rather than
  re-deriving chain-integrity logic a third time. This is verifier-composes-
  with-verifier, not verifier-trusts-production -- confirmed by the
  AST-parse test in tests/test_cain41_universal_proof.py, which checks this
  module imports neither cain_universal_proof_41 nor cain_evidence_fabric_37.

Central design point this module exists to prove: "one compromised proof
subsystem must not silently invalidate the meaning of another." A
UniversalAgentProof references sub-proofs from several independent chains;
verify_universal_proof() below returns a PER-SUB-PROOF verdict, not a single
collapsed boolean, so a tampered economic chain and a clean organization
chain referenced by the same composition are reported distinctly.
"""

from __future__ import annotations

import hashlib
import json
import time
from typing import Any, Dict, List, Optional

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

import cain_37_independent_verifier as chain_verifier

KNOWN_ALGORITHMS = {"Ed25519-SHA256"}


class Verdict:
    VALID = "VALID"
    INVALID = "INVALID"
    EXPIRED = "EXPIRED"
    REVOKED = "REVOKED"
    UNKNOWN = "UNKNOWN"
    INSUFFICIENT_EVIDENCE = "INSUFFICIENT_EVIDENCE"


def _canonical_bytes(obj: Any) -> bytes:
    """Independently reimplemented -- same rule as
    cain_universal_proof_41.py's docstring describes, not imported from it."""
    return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False, default=str).encode("utf-8")


def _sha256_hex(data: bytes) -> str:
    return hashlib.sha256(data).hexdigest()


def _proof_content_hash(proof: Dict[str, Any]) -> str:
    fields = ("proof_id", "agent_id", "principal", "organization_id", "sub_proofs",
              "issued_at", "expires_at", "epoch", "sequence", "schema_version",
              "revoked", "revocation_reason")
    d = {k: proof.get(k) for k in fields}
    return _sha256_hex(_canonical_bytes(d))


def verify_proof_signature(proof: Dict[str, Any]) -> Dict[str, Any]:
    """Phase 8 defenses built in directly:
    - algorithm confusion: an unrecognized or missing algorithm is rejected
      outright, even if a 'signature' field is present (guards the classic
      alg=none-style downgrade).
    - missing/truncated fields: required fields are checked before any
      cryptographic work is attempted.
    """
    required = ("proof_id", "agent_id", "sub_proofs", "issued_at", "expires_at", "signature", "algorithm", "parent_public_key_b64")
    missing = [f for f in required if f not in proof or proof[f] in (None, "")]
    # signature/algorithm/parent_public_key_b64 empty is a distinct case (unsigned), handled below
    hard_missing = [f for f in required if f not in proof]
    if hard_missing:
        return {"verdict": Verdict.INSUFFICIENT_EVIDENCE, "reason": f"TRUNCATED_PROOF: missing fields {hard_missing}"}

    algorithm = proof.get("algorithm", "")
    if algorithm not in KNOWN_ALGORITHMS:
        return {"verdict": Verdict.INVALID, "reason": f"UNKNOWN_OR_UNSUPPORTED_ALGORITHM: '{algorithm}'"}

    if not proof.get("signature") or not proof.get("parent_public_key_b64"):
        return {"verdict": Verdict.INVALID, "reason": "UNSIGNED_PROOF"}

    if not HAS_ED25519:
        return {"verdict": Verdict.INSUFFICIENT_EVIDENCE, "reason": "ED25519_UNAVAILABLE"}

    try:
        public_key = ed25519.Ed25519PublicKey.from_public_bytes(bytes.fromhex(proof["parent_public_key_b64"]))
        digest = bytes.fromhex(_proof_content_hash(proof))
        public_key.verify(bytes.fromhex(proof["signature"]), digest)
        return {"verdict": Verdict.VALID, "reason": "SIGNATURE_VALID"}
    except (InvalidSignature, ValueError) as e:
        return {"verdict": Verdict.INVALID, "reason": f"SIGNATURE_INVALID: {type(e).__name__}"}


def verify_freshness_and_revocation(proof: Dict[str, Any], now: Optional[float] = None) -> Dict[str, Any]:
    now = now if now is not None else time.time()
    if proof.get("revoked"):
        return {"verdict": Verdict.REVOKED, "reason": proof.get("revocation_reason", "no reason given")}
    if now > proof.get("expires_at", 0):
        return {"verdict": Verdict.EXPIRED, "reason": f"expired at {proof.get('expires_at')}, checked at {now}"}
    return {"verdict": Verdict.VALID, "reason": "FRESH"}


def verify_sub_proof_membership(sub_proof: Dict[str, Any], chain_records: List[Dict[str, Any]]) -> Dict[str, Any]:
    """Finds the referenced evidence_id in the ACTUAL chain records (not in
    the composition's own claim) and independently checks:
    1. it exists at all (INSUFFICIENT_EVIDENCE if not)
    2. its content_hash -- RECOMPUTED from the raw evidence fields, never
       read from the record's own stored 'content_hash' value -- matches
       what the composition claims (INVALID if tampered since composition).
       Recomputing independently matters: a tamper that changes an evidence
       field WITHOUT also updating the stored content_hash string (e.g. a
       naive attacker, or simply a bug) would be invisible to a check that
       only compares two stored strings against each other.
    3. its cluster_id matches what the composition claims (INVALID,
       CROSS_CHAIN_SPLICE_DETECTED, if an evidence_id from one
       cluster/organization/escrow context was spliced into a reference
       claiming a different one)
    """
    evidence_id = sub_proof.get("evidence_id")
    matching = [r for r in chain_records if r["evidence"].get("evidence_id") == evidence_id]
    if not matching:
        return {"verdict": Verdict.INSUFFICIENT_EVIDENCE, "reason": f"evidence_id '{evidence_id}' not found in referenced chain"}
    record = matching[0]

    actual_content_hash = chain_verifier._content_hash(record["evidence"])
    claimed_content_hash = sub_proof.get("content_hash")
    if actual_content_hash != claimed_content_hash:
        return {"verdict": Verdict.INVALID, "reason": f"CONTENT_HASH_MISMATCH: independently recomputed {actual_content_hash}, composition claims {claimed_content_hash}"}

    actual_cluster_id = record["evidence"].get("cluster_id")
    claimed_cluster_id = sub_proof.get("cluster_id")
    if actual_cluster_id != claimed_cluster_id:
        return {"verdict": Verdict.INVALID, "reason": f"CROSS_CHAIN_SPLICE_DETECTED: evidence belongs to cluster_id '{actual_cluster_id}', composition claims '{claimed_cluster_id}'"}

    return {"verdict": Verdict.VALID, "reason": "SUB_PROOF_MEMBERSHIP_CONFIRMED"}


def verify_universal_proof(proof: Dict[str, Any], chain_records_by_file: Dict[str, List[Dict[str, Any]]], now: Optional[float] = None) -> Dict[str, Any]:
    """Top-level composition check. Returns a per-sub-proof breakdown --
    NEVER a single collapsed boolean -- so a compromised subsystem's
    evidence is visible without invalidating an unrelated, clean
    subsystem's evidence in the same composition."""
    sig_result = verify_proof_signature(proof)
    if sig_result["verdict"] != Verdict.VALID:
        return {"overall_verdict": sig_result["verdict"], "signature": sig_result, "freshness": None, "sub_proofs": []}

    freshness_result = verify_freshness_and_revocation(proof, now=now)

    sub_results = []
    any_invalid = False
    for sp in proof.get("sub_proofs", []):
        chain_file = sp.get("chain_file")
        chain_records = chain_records_by_file.get(chain_file, [])
        if not chain_records:
            result = {"verdict": Verdict.INSUFFICIENT_EVIDENCE, "reason": f"chain_file '{chain_file}' not provided to verifier"}
        else:
            result = verify_sub_proof_membership(sp, chain_records)
        sub_results.append({"proof_type": sp.get("proof_type"), "evidence_id": sp.get("evidence_id"), "chain_file": chain_file, **result})
        if result["verdict"] != Verdict.VALID:
            any_invalid = True

    if freshness_result["verdict"] != Verdict.VALID:
        overall = freshness_result["verdict"]
    elif any_invalid:
        overall = Verdict.INVALID
    else:
        overall = Verdict.VALID

    return {
        "overall_verdict": overall,
        "signature": sig_result,
        "freshness": freshness_result,
        "sub_proofs": sub_results,
    }
