# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-an-a2a-v1-0-agent-card-as-a-discovery-time-liability-rather-than-a-capability-advertisement.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-an-a2a-v1-0-agent-card-as-a-discovery-time-liability-rather-than-a-capability-advertisement.warrant.json
# Markdown SHA-256:   6a74416df1c7b74aacbb5b451c6589393e2864b7b2f45d7d1943d7a8d6da4ac0
# Code AST SHA-256:   3c0a66ebf9c80d5e67dea2c32ad4f235157cbf1ef13cd8be336e4eed359eed10
# Verified Classes:   CardWarrantViolation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class CardWarrantViolation(RuntimeError):
    """Raised when a client binds a task lifecycle to an Agent Card's advertised
    state vocabulary without covering the full canonical A2A state set."""
    pass

CANONICAL_STATES = {"submitted", "working", "input-required", "completed", "failed", "canceled"}
NON_TERMINAL_REQUIRING_ACTION = {"input-required"}


def bind_task_webhook(card: dict, client_handlers: dict, push_url: str) -> dict:
    """Validate that the client can service every non-terminal state the remote
    agent may enter, before committing a push-notification binding."""
    if not card.get("capabilities", {}).get("pushNotifications", {}).get("supported"):
        raise CardWarrantViolation(
            f"card for {card.get('name')} does not advertise pushNotifications; "
            "webhook binding would be a no-op"
        )

    advertised = set(card.get("capabilities", {}).get("stateTransitionHistory") and
                     CANONICAL_STATES or CANONICAL_STATES)
    uncovered = NON_TERMINAL_REQUIRING_ACTION - set(client_handlers)

    if uncovered:
        raise CardWarrantViolation(
            f"client handlers cover {sorted(client_handlers)} but remote agent "
            f"may enter {sorted(uncovered)}; webhook would never fire for these "
            f"states and task would orphan. Card advertised states: {sorted(advertised)}"
        )

    if not push_url.startswith("https://"):
        raise CardWarrantViolation(f"pushNotification.url must be https, got {push_url!r}")

    return {
        "task_binding": push_url,
        "handled_states": sorted(client_handlers),
        "requires_poll_for": sorted(NON_TERMINAL_REQUIRING_ACTION),
        "card_is_routing_hint_only": True,
    }


def reconcile_orphaned_task(task: dict, handlers: dict) -> str:
    """Called by the reconciliation poller for tasks whose webhook never fired."""
    state = task.get("status", {}).get("state")
    if state in NON_TERMINAL_REQUIRING_ACTION and state not in handlers:
        raise CardWarrantViolation(
            f"task {task.get('id')} orphaned in {state!r}; no handler and no "
            f"continuation path — card-derived lifecycle assumption invalid"
        )
    return state
