# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-a-signed-agent-card-against-the-live-capability-surface-before-a2a-v1-0-trust-negotiation-completes.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-a-signed-agent-card-against-the-live-capability-surface-before-a2a-v1-0-trust-negotiation-completes.warrant.json
# Markdown SHA-256:   4aef566156690d4ae88538d30dd584fc879b78a0974772a60531574702ca2c85
# Code AST SHA-256:   5c433c454fb3ba04c6ae1a0670f8ef58f89e53e453afcbfb17577ca511398365
# Verified Classes:   CapabilityReconciliationError, SignedCard, NegotiationResponse
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class CapabilityReconciliationError(RuntimeError):
    """Raised when a negotiated A2A capability surface diverges from the signed Agent Card."""

    def __init__(self, peer: str, reason: str, delta: dict):
        self.peer = peer
        self.reason = reason
        self.delta = delta
        super().__init__(f"{peer}: {reason} | delta={delta}")


@dataclass(frozen=True)
class SignedCard:
    peer_id: str
    scopes: frozenset[str]
    skill_schema_hashes: dict[str, str]  # skill_id -> declared schema hash


@dataclass(frozen=True)
class NegotiationResponse:
    peer_id: str
    negotiated_scopes: frozenset[str]
    negotiated_skills: frozenset[str]
    live_schema_hashes: dict[str, str]  # skill_id -> live schema hash (may be empty)


def reconcile_before_commit(
    card: SignedCard,
    resp: NegotiationResponse,
    signature_valid: bool,
    required_scopes: frozenset[str],
) -> None:
    if not signature_valid:
        raise CapabilityReconciliationError(
            card.peer_id, "signature_invalid", {}
        )

    if resp.peer_id != card.peer_id:
        raise CapabilityReconciliationError(
            card.peer_id, "peer_id_mismatch", {"card": card.peer_id, "resp": resp.peer_id}
        )

    extra_scopes = resp.negotiated_scopes - card.scopes
    if extra_scopes:
        # Over-granting peer: treat as misconfiguration, fail closed.
        raise CapabilityReconciliationError(
            card.peer_id, "peer_over_grant", {"extra_scopes": sorted(extra_scopes)}
        )

    unknown_skills = resp.negotiated_skills - frozenset(card.skill_schema_hashes)
    if unknown_skills:
        raise CapabilityReconciliationError(
            card.peer_id, "undeclared_skill", {"skills": sorted(unknown_skills)}
        )

    # Semantic divergence: skill ID matches but live schema hash differs from card.
    for skill in resp.negotiated_skills:
        declared = card.skill_schema_hashes[skill]
        live = resp.live_schema_hashes.get(skill)
        if live is None:
            # Protocol did not expose live hash; caller must have probed.
            raise CapabilityReconciliationError(
                card.peer_id,
                "unverified_skill_schema",
                {"skill": skill, "declared": declared},
            )
        if live != declared:
            raise CapabilityReconciliationError(
                card.peer_id,
                "schema_divergence",
                {"skill": skill, "declared": declared, "live": live},
            )

    missing_required = required_scopes - resp.negotiated_scopes
    if missing_required:
        raise CapabilityReconciliationError(
            card.peer_id,
            "insufficient_scope_for_plan",
            {"missing": sorted(missing_required)},
        )
    # Reconciliation passed: caller may now commit the warrant and issue tasks.
