# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-complete-an-a2a-capability-handshake-with-a-federated-peer-across-organizational-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-complete-an-a2a-capability-handshake-with-a-federated-peer-across-organizational-boundaries.warrant.json
# Markdown SHA-256:   f31fd306527213969d8e868d3f30330c8e631adc5cadc60d447635d5c4210eef
# Code AST SHA-256:   185b0f0d0b7a669d48c5ff42104fe3c256dd58bcfc511e6a99bd380806d09d3e
# Verified Classes:   FederationHandshakeRefused, HandshakeContext
# Defensive Guards:   5 fail-closed invariants (zero external deps)

# a2a_federation_handshake.py
# Operational guard for cross-org A2A capability handshakes.
# Encodes the "verifiable-at-completion-time" invariant.

from dataclasses import dataclass
from typing import Optional


class FederationHandshakeRefused(RuntimeError):
    """Raised when an A2A handshake cannot be soundly completed.

    Distinct from a negotiation failure (empty capability intersection).
    This signals that the protocol may have succeeded but the trust
    layer could not justify the grant at completion time.
    """
    pass


@dataclass(frozen=True)
class HandshakeContext:
    peer_issuer: str
    peer_subject: str
    signing_anchor: Optional[str]       # anchor id resolved from current set
    anchor_in_current_set: bool
    key_source: str                     # "live" | "cache"
    key_cache_ttl_expired: bool
    kid_unique_in_resolved_set: bool
    subject_bound_to_grant: bool
    card_expires_at: float
    local_now: float
    clock_skew_tolerance_s: float


def complete_handshake(ctx: HandshakeContext) -> str:
    """Return a grant token only if all validity conditions hold.

    Any unverifiable condition is treated as refusal, not acceptance.
    """
    if ctx.signing_anchor is None or not ctx.anchor_in_current_set:
        raise FederationHandshakeRefused(
            f"anchor unresolvable or revoked for issuer={ctx.peer_issuer}"
        )

    # Stale-key cache hit: signature may verify but is not a proof.
    if ctx.key_source == "cache" and ctx.key_cache_ttl_expired:
        raise FederationHandshakeRefused(
            f"stale key cache for issuer={ctx.peer_issuer}; re-resolve JWKS"
        )

    if not ctx.kid_unique_in_resolved_set:
        raise FederationHandshakeRefused(
            f"kid ambiguous in resolved key set for issuer={ctx.peer_issuer}"
        )

    # Issuer-scoped grant reuse: issuer trusted, subject not individually bound.
    if not ctx.subject_bound_to_grant:
        raise FederationHandshakeRefused(
            f"subject={ctx.peer_subject} not bound to capability grant"
        )

    if ctx.card_expires_at <= ctx.local_now - ctx.clock_skew_tolerance_s:
        raise FederationHandshakeRefused(
            f"card expired beyond skew for subject={ctx.peer_subject}"
        )

    # All conditions verifiable: name anchor, key, subject.
    return f"grant:{ctx.peer_issuer}|{ctx.peer_subject}|{ctx.signing_anchor}"
