# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-inherit-a-peer-s-aaif-identity-attestation-across-a-federated-a2a-hop.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-inherit-a-peer-s-aaif-identity-attestation-across-a-federated-a2a-hop.warrant.json
# Markdown SHA-256:   f9a3446af0f9a116c499980c42d96ff0b77d0a49b69dce5558a7e7988bce7b39
# Code AST SHA-256:   a656ae71de50b19cb18d78577576d026c29f646e2d7f96aaec92b98a9da48c2d
# Verified Classes:   AttestationBindingError, Attestation, PresentingInstance
# Defensive Guards:   8 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class AttestationBindingError(RuntimeError):
    """Raised when an inherited AAIF attestation does not bind to the presenting instance."""


@dataclass
class Attestation:
    issuer: str
    subject_key_id: str
    capabilities: set
    audience_realms: set
    issued_at: float
    expires_at: float
    signature_valid: bool


@dataclass
class PresentingInstance:
    instance_id: str
    controlled_key_ids: set
    cold_start_ts: float
    can_prove_possession: bool = True


def verify_hop(
    att: Attestation,
    presenter: PresentingInstance,
    verifier_realm: str,
    now: float | None = None,
    delegation_chain: list | None = None,
) -> None:
    now = now if now is not None else time.time()

    if not att.signature_valid:
        raise AttestationBindingError(f"signature invalid for issuer {att.issuer}")
    if now >= att.expires_at:
        raise AttestationBindingError(f"attestation expired at {att.expires_at}")
    if verifier_realm not in att.audience_realms:
        raise AttestationBindingError(
            f"realm {verifier_realm} not in audience {att.audience_realms}; "
            "pass-through across realm boundary is not permitted"
        )

    # Subject continuity: the presenter must control the subject key, OR be a
    # named terminal delegate with a capability subset.
    controls_subject = att.subject_key_id in presenter.controlled_key_ids

    if not controls_subject:
        if not delegation_chain:
            raise AttestationBindingError(
                f"presenter {presenter.instance_id} does not control subject key "
                f"{att.subject_key_id} and presents no delegation chain "
                "(inherited attestation from snapshot or parent context)"
            )
        terminal = delegation_chain[-1]
        if terminal.get("delegate_key_id") not in presenter.controlled_key_ids:
            raise AttestationBindingError(
                f"delegation chain terminal key {terminal.get('delegate_key_id')} "
                f"not held by presenter {presenter.instance_id}"
            )
        if not set(terminal.get("capabilities", set())).issubset(att.capabilities):
            raise AttestationBindingError(
                "delegated capability set exceeds parent attestation scope"
            )

    # Cold-start lineage check: a snapshot-restored instance predating iat
    # cannot have earned the credential; require proof-of-possession.
    if presenter.cold_start_ts < att.issued_at and not controls_subject:
        raise AttestationBindingError(
            f"presenter {presenter.instance_id} cold-started at "
            f"{presenter.cold_start_ts} before attestation issuance "
            f"{att.issued_at}; credential presumed inherited"
        )

    if not presenter.can_prove_possession and not delegation_chain:
        raise AttestationBindingError(
            f"presenter {presenter.instance_id} cannot prove possession of "
            f"subject key {att.subject_key_id}"
        )


def handle_federated_call(att, presenter, verifier_realm, delegation_chain=None):
    verify_hop(att, presenter, verifier_realm, delegation_chain=delegation_chain)
    return {"accepted": True, "subject": att.subject_key_id,
            "executor": presenter.instance_id}
