# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-accepts-a-delegated-capability-whose-policy-predicate-is-evaluated-against-the-wrong-subject.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-accepts-a-delegated-capability-whose-policy-predicate-is-evaluated-against-the-wrong-subject.warrant.json
# Markdown SHA-256:   f0d958983901750614379029ed7c1e0eb5c9eba184f8911697d0eed85aa33abc
# Code AST SHA-256:   75b989890fe5168edcf1044785810ba4d5dabcc032318dcaeff2ff5c8c0b88bd
# Verified Classes:   PolicyReconciliationError, Caveat, LatticeMapping
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional

class PolicyReconciliationError(RuntimeError):
    """Raised when a cross-org caveat cannot be soundly evaluated locally."""
    pass

@dataclass(frozen=True)
class Caveat:
    key: str
    value: str
    issuer_org: str
    issuer_policy_version: str

@dataclass(frozen=True)
class LatticeMapping:
    issuer_policy_version: str
    evaluator_policy_version: str
    # maps issuer enum value -> evaluator enum value; signed by both orgs
    translation: dict
    signed: bool

def resolve_effective_subject(verified_chain: list) -> str:
    # last hop's delegate is the only valid subject; never session cache
    if not verified_chain:
        raise PolicyReconciliationError("empty delegation chain; no effective subject")
    return verified_chain[-1].delegate

def evaluate_caveat(
    caveat: Caveat,
    evaluator_org: str,
    evaluator_policy_version: str,
    mapping: Optional[LatticeMapping],
    verified_chain: list,
) -> bool:
    # Subject binding must be recomputed from the chain, not trusted from session.
    effective_subject = resolve_effective_subject(verified_chain)
    if caveat.key == "subject" and caveat.value != effective_subject:
        # A subject caveat that does not match the present holder is a hard deny.
        raise PolicyReconciliationError(
            f"subject caveat '{caveat.value}' != effective subject '{effective_subject}'"
        )

    if caveat.issuer_org == evaluator_org:
        # Same lattice; raw evaluation is sound.
        return _raw_eval(caveat, evaluator_policy_version)

    # Cross-org: require a signed, version-matched mapping.
    if mapping is None or not mapping.signed:
        raise PolicyReconciliationError(
            f"no signed lattice mapping for issuer '{caveat.issuer_org}' "
            f"policy v{caveat.issuer_policy_version}"
        )
    if mapping.issuer_policy_version != caveat.issuer_policy_version:
        raise PolicyReconciliationError(
            f"mapping is for issuer policy v{mapping.issuer_policy_version}, "
            f"caveat authored under v{caveat.issuer_policy_version}"
        )
    if mapping.evaluator_policy_version != evaluator_policy_version:
        raise PolicyReconciliationError(
            f"mapping targets evaluator v{mapping.evaluator_policy_version}, "
            f"running v{evaluator_policy_version}; renegotiate"
        )

    translated = mapping.translation.get(caveat.value)
    if translated is None:
        raise PolicyReconciliationError(
            f"issuer value '{caveat.value}' has no mapping into evaluator lattice"
        )
    return _raw_eval(Caveat(caveat.key, translated, evaluator_org, evaluator_policy_version),
                     evaluator_policy_version)

def _raw_eval(caveat: Caveat, evaluator_policy_version: str) -> bool:
    # placeholder for the local predicate engine; ordering is evaluator-local
    return True
