# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-verify-a-signed-agent-card-chain-when-the-leaf-key-rotates-mid-handoff-and-the-parent-signature-was-minted-over-a-stale-capabil.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-verify-a-signed-agent-card-chain-when-the-leaf-key-rotates-mid-handoff-and-the-parent-signature-was-minted-over-a-stale-capabil.warrant.json
# Markdown SHA-256:   b23efa12d2530aba95f982041a35fd825d1020291909522ed3e1be28b82b0787
# Code AST SHA-256:   390f37c2832bd856787c673d2ccbe48ce3f66241e47d4c242f3e8988eb61bae0
# Verified Classes:   AttestationChainError, SignedCard, RotationProof
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import hashlib
import hmac
from dataclasses import dataclass
from typing import Optional


class AttestationChainError(RuntimeError):
    """Raised when a signed Agent Card chain fails a joint-tuple invariant."""


@dataclass(frozen=True)
class SignedCard:
    signing_key: bytes
    capability_hash: str
    validity_window: tuple[int, int]
    parent_signature: bytes
    canonical_bytes: bytes


@dataclass(frozen=True)
class RotationProof:
    old_key: bytes
    new_key: bytes
    capability_hash_at_rotation: str
    timestamp: int
    parent_signature: bytes


def _canonical_hash(card: SignedCard) -> str:
    return hashlib.sha256(card.canonical_bytes).hexdigest()


def verify_chain(
    card: SignedCard,
    envelope_signature: bytes,
    envelope_key: bytes,
    envelope_payload: bytes,
    rotation_proof: Optional[RotationProof],
    pinned_issuer_key: bytes,
    now: int,
) -> str:
    """
    Pure verification: NO network I/O in any failure branch.
    Returns the accepted capability_hash on success.
    """
    # 1. Parent signature must cover the exact canonical bytes presented.
    expected = hmac.new(pinned_issuer_key, card.canonical_bytes, hashlib.sha256).digest()
    if not hmac.compare_digest(expected, card.parent_signature):
        raise AttestationChainError("parent signature does not cover presented card bytes")

    # 2. Validity window is part of the signed tuple.
    start, end = card.validity_window
    if not (start <= now <= end):
        raise AttestationChainError(f"card outside signed validity window at {now}")

    # 3. Envelope must be signed by the key the parent attested.
    if envelope_key != card.signing_key:
        # Key mismatch: admissible ONLY via a parent-signed rotation proof.
        if rotation_proof is None:
            raise AttestationChainError(
                "key mismatch with absent rotation proof; refusing to re-fetch"
            )
        proof_ok = hmac.compare_digest(
            hmac.new(pinned_issuer_key, _proof_bytes(rotation_proof), hashlib.sha256).digest(),
            rotation_proof.parent_signature,
        )
        if not proof_ok:
            raise AttestationChainError("rotation proof not countersigned by pinned issuer")
        if rotation_proof.old_key != card.signing_key or rotation_proof.new_key != envelope_key:
            raise AttestationChainError("rotation proof does not chain old->new key")
        if rotation_proof.capability_hash_at_rotation != card.capability_hash:
            raise AttestationChainError(
                "rotation changed capability hash; requires fresh parent countersignature"
            )

    # 4. Envelope signature must verify under the (possibly rotated) attested key.
    env_expected = hmac.new(envelope_key, envelope_payload, hashlib.sha256).digest()
    if not hmac.compare_digest(env_expected, envelope_signature):
        raise AttestationChainError("handoff envelope signature invalid under attested key")

    # 5. Log the accepted capability hash so capability-layer drift is auditable.
    return card.capability_hash


def _proof_bytes(p: RotationProof) -> bytes:
    return b"|".join([p.old_key, p.new_key, p.capability_hash_at_rotation.encode(), str(p.timestamp).encode()])
