# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-a2a-agent-card-has-been-silently-re-signed-under-a-rotated-key-mid-delegation-and-why-the-handshake-succeeds-anywa.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-a2a-agent-card-has-been-silently-re-signed-under-a-rotated-key-mid-delegation-and-why-the-handshake-succeeds-anywa.warrant.json
# Markdown SHA-256:   25497c6944026476ee9d7c2d834959de94cc61ba8b535b3ab0610aa38d851a38
# Code AST SHA-256:   694c57fe8c4db57572417f0ece56a41cbc136cc45c918b2226c754ff6e0f5a77
# Verified Classes:   WarrantContinuityError, ContextWarrant, AgentCard
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class WarrantContinuityError(RuntimeError):
    """Raised when a task context's authorizing key is no longer resolvable
    and no signed key-succession record bridges the gap."""
    pass


@dataclass
class ContextWarrant:
    context_id: str
    task_id: str
    authorizing_key_id: str
    opened_at: float
    succession_chain: list = field(default_factory=list)  # signed transitions only


@dataclass
class AgentCard:
    signing_key_id: str
    jwks_uri: str
    # A2A v1.0 has no `previous_key_id` / succession field; absent here too.
    previous_key_id: Optional[str] = None


def verify_response_under_context(
    warrant: ContextWarrant,
    card: AgentCard,
    current_jwks: dict,
    response_kid: str,
    now: Optional[float] = None,
) -> bool:
    now = now if now is not None else time.time()

    # Check 1: does the response verify under the *current* card key?
    if response_kid not in current_jwks:
        raise WarrantContinuityError(
            f"response kid={response_kid} not in JWKS; cannot verify at all"
        )
    response_ok = response_kid == card.signing_key_id

    # Check 2 (the one the protocol omits): is the context's authorizing key
    # still resolvable, or bridged by a signed succession record?
    authorizing_key_present = warrant.authorizing_key_id in current_jwks
    bridged = any(
        step.get("from") == warrant.authorizing_key_id
        and step.get("to") == card.signing_key_id
        and step.get("signature_verified") is True
        for step in warrant.succession_chain
    )

    if not authorizing_key_present and not bridged:
        # The authorizing key is gone and no signed succession exists.
        # Response verification being green is irrelevant: the warrant is void.
        raise WarrantContinuityError(
            f"context {warrant.context_id} authorized under "
            f"{warrant.authorizing_key_id!r}, which has left the JWKS; "
            f"current card key {card.signing_key_id!r} is not a signed "
            f"successor (previous_key_id={card.previous_key_id!r}). "
            f"response_verified={response_ok}. Abort and re-open context."
        )

    if warrant.authorizing_key_id != card.signing_key_id and not bridged:
        # Overlap window: old key still resolvable. Continue, but pin
        # verification to the authorizing key, not the card's current key.
        if response_kid != warrant.authorizing_key_id:
            raise WarrantContinuityError(
                f"context {warrant.context_id} pinned to "
                f"{warrant.authorizing_key_id!r} but response signed by "
                f"{response_kid!r} during overlap; reject or re-bind explicitly"
            )
        return True

    return response_ok


def handle_delegation_response(
    warrant: ContextWarrant,
    card: AgentCard,
    current_jwks: dict,
    response_kid: str,
) -> str:
    try:
        verify_response_under_context(warrant, card, current_jwks, response_kid)
        return "accepted"
    except WarrantContinuityError as e:
        # Fail closed: do not continue the context; surface for re-open.
        raise WarrantContinuityError(
            f"delegation context continuity broken: {e}"
        ) from e
