# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-a2a-agent-card-is-advertising-a-task-lifecycle-state-machine-the-caller-cannot-legally-drive.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-a2a-agent-card-is-advertising-a-task-lifecycle-state-machine-the-caller-cannot-legally-drive.warrant.json
# Markdown SHA-256:   59bdc2d439af3d393a0accc28d5b2805687356fd58756f17b6926bdaa5f5587a
# Code AST SHA-256:   c5710c69265f11bc03b0a58d558039026b9a9fed25f165dae71746ccde0d3e43
# Verified Classes:   A2ACardConformanceError, AuthoritativeChannel, ObservationPolicy
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import enum
from dataclasses import dataclass


class A2ACardConformanceError(RuntimeError):
    """Raised when a discovered Agent Card implies a task lifecycle the caller cannot legally drive."""
    pass


class AuthoritativeChannel(enum.Enum):
    PUSH = "push"
    POLL = "poll"
    STREAM = "stream"


@dataclass(frozen=True)
class ObservationPolicy:
    authoritative_channel: AuthoritativeChannel
    history_available: bool
    reap_assumption: str  # "caller_must_supply_push" | "poll_is_best_effort"


def compile_observation_policy(card_capabilities: dict) -> ObservationPolicy:
    streaming = bool(card_capabilities.get("streaming", False))
    push = bool(card_capabilities.get("pushNotifications", False))
    history = bool(card_capabilities.get("stateTransitionHistory", False))

    if streaming:
        return ObservationPolicy(AuthoritativeChannel.STREAM, history, "stream_is_authoritative")

    if push and not streaming:
        # The dangerous composition: push is the only authoritative channel,
        # poll is a stale read, and history is (usually) disabled.
        return ObservationPolicy(
            AuthoritativeChannel.PUSH,
            history,
            "caller_must_supply_push",
        )

    if not push and not streaming:
        return ObservationPolicy(
            AuthoritativeChannel.POLL,
            history,
            "poll_is_best_effort",
        )

    raise A2ACardConformanceError(
        f"Unclassifiable capability triple: streaming={streaming}, "
        f"pushNotifications={push}, stateTransitionHistory={history}"
    )


def send_task(policy: ObservationPolicy, push_url: str | None) -> dict:
    if policy.authoritative_channel is AuthoritativeChannel.PUSH and push_url is None:
        # The card declared pushNotifications:true but the caller wired no push URL.
        # Polling would observe a stale 'working' forever; cancel would hit TaskNotFoundError
        # after the remote reaps. Refuse pre-flight instead of hanging.
        raise A2ACardConformanceError(
            "Agent Card declares pushNotifications:true with streaming:false; "
            "push URL is mandatory for terminal observation. Refusing to send on stale channel."
        )
    return {"push_url": push_url, "channel": policy.authoritative_channel.value}


def reconcile_cancel_error(policy: ObservationPolicy, push_log_has_terminal: bool) -> str:
    if policy.authoritative_channel is AuthoritativeChannel.PUSH and push_log_has_terminal:
        # TaskNotFoundError on cancel is a reap, not a loss. Do not re-send.
        return "reaped_after_terminal:do_not_resend"
    if policy.authoritative_channel is AuthoritativeChannel.PUSH and not push_log_has_terminal:
        raise A2ACardConformanceError(
            "Cancel returned TaskNotFoundError with no terminal push observed: "
            "task state is unreconcilable; caller must not retry blindly."
        )
    return "reconcile_via_poll"
