# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-an-a2a-task-acceptance-when-the-remote-agent-card-s-declared-taskstate-transition-graph-is-acyclic-but-the-l.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-an-a2a-task-acceptance-when-the-remote-agent-card-s-declared-taskstate-transition-graph-is-acyclic-but-the-l.warrant.json
# Markdown SHA-256:   086518a3bb11e59a50671182f7e2ed9192defb13f164bc413828c01d2b49d7e7
# Code AST SHA-256:   0c40c6d667fcd3f7071245a674b55b6b6a5b06133be9f963a4957b9a6f1b041c
# Verified Classes:   ClarificationBudgetExceeded, AgentCard, ArtifactSchema
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ClarificationBudgetExceeded(RuntimeError):
    """Raised when the local artifact schema demands more clarification rounds
    than the remote A2A agent card permits via its declared state transitions."""
    pass


@dataclass
class AgentCard:
    state_transitions: list[tuple[str, str]]
    max_reentries: Optional[int] = None  # extension field, A2A v1.0


@dataclass
class ArtifactSchema:
    nullable_required_fields: list[str]
    batched_clarification: bool = False


def compute_clarification_budget(card: AgentCard) -> float:
    has_self_loop = ("input-required", "input-required") in card.state_transitions
    if has_self_loop:
        return float("inf")
    if card.max_reentries is not None:
        return card.max_reentries
    # single edge input-required -> working, no annotation
    if ("input-required", "working") in card.state_transitions:
        return 1
    return 0


def compute_clarification_demand(schema: ArtifactSchema) -> int:
    if schema.batched_clarification:
        # batching collapses to one round, but completeness is unverified
        return 1
    return len(schema.nullable_required_fields)


def preflight_accept(card: AgentCard, schema: ArtifactSchema) -> None:
    budget = compute_clarification_budget(card)
    demand = compute_clarification_demand(schema)
    if demand > budget:
        raise ClarificationBudgetExceeded(
            f"refusing tasks/send: artifact schema demands {demand} clarification "
            f"round(s) (fields={schema.nullable_required_fields}, "
            f"batched={schema.batched_clarification}) but remote card permits "
            f"only {budget} re-entry into 'input-required'. Accepting would strand "
            f"the task after the {int(budget) + 1}th missing-field discovery, "
            f"discarding any prior user clarification."
        )
