# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-an-a2a-v1-0-agent-card-whose-declared-capabilities-pushnotifications-and-defaultinputmodes-diverge-from-the-live-task.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-an-a2a-v1-0-agent-card-whose-declared-capabilities-pushnotifications-and-defaultinputmodes-diverge-from-the-live-task.warrant.json
# Markdown SHA-256:   ffdc0de5ac5daafbe1786e798dd1307012bfac7b9f5533dac8a33e68cd3c7fbd
# Code AST SHA-256:   fb1f04f527142fdc3431a04f2529e08df84f30e59b4dbefebd203f3eaddd7e68
# Verified Classes:   PushBindingInvariantError, PushHealth, TaskStatus, AgentCard, TaskRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class PushBindingInvariantError(RuntimeError):
    """Raised when a client treats Agent Card push capability as a delivery guarantee
    and has no poll fallback armed for a task whose webhook binding has failed."""


class PushHealth(Enum):
    HEALTHY = "healthy"
    DEGRADED = "degraded"
    FAILED = "failed"


class TaskStatus(Enum):
    SUBMITTED = "submitted"
    WORKING = "working"
    INPUT_REQUIRED = "input-required"
    COMPLETED = "completed"
    CANCELED = "canceled"


@dataclass
class AgentCard:
    push_notifications: bool
    state_transition_history: bool


@dataclass
class TaskRecord:
    task_id: str
    status: TaskStatus
    push_config_id: Optional[str]
    push_health: PushHealth = PushHealth.HEALTHY
    last_status_change: float = field(default_factory=time.time)
    poll_fallback_armed: bool = False


def on_webhook_delivery_failure(task: TaskRecord, http_status: int) -> TaskRecord:
    """Handle a webhook POST failure per A2A v1.0 semantics.

    A 410 Gone (or any non-429 4xx) invalidates the binding; the server will not
    retry. The client MUST arm a poll fallback or it will deadlock in 'working'.
    """
    if http_status == 429:
        # Rate-limited: transient, server will retry. Do not demote.
        return task

    if http_status == 410 or 400 <= http_status < 500:
        task.push_health = PushHealth.FAILED
        task.push_config_id = None
        # Invariant: a failed binding on a non-terminal task requires a poll fallback.
        if task.status in (TaskStatus.WORKING, TaskStatus.INPUT_REQUIRED):
            if not task.poll_fallback_armed:
                raise PushBindingInvariantError(
                    f"task {task.task_id} in {task.status.value} with webhook "
                    f"HTTP {http_status}: push binding invalidated but no poll "
                    f"fallback armed. Card capability pushNotifications=true is "
                    f"not a delivery guarantee; arm polling before continuing."
                )
        return task

    if 500 <= http_status < 600:
        task.push_health = PushHealth.DEGRADED
        return task

    raise PushBindingInvariantError(
        f"unexpected webhook status {http_status} for task {task.task_id}"
    )


def reconcile_rebind(task: TaskRecord, get_response_push_config_id: Optional[str]) -> TaskRecord:
    """After a pushNotificationConfig/set, reconcile against tasks/get metadata.

    The 'set' 200 OK is not authoritative; Task.metadata.pushConfigId from
    tasks/get is. Matching on the pre-rebind ID will produce a spurious cancel.
    """
    if task.push_health == PushHealth.FAILED and get_response_push_config_id is None:
        raise PushBindingInvariantError(
            f"task {task.task_id}: rebind acknowledged by set but tasks/get "
            f"still reports no pushConfigId; do not cancel on stale-ID mismatch"
        )
    task.push_config_id = get_response_push_config_id
    task.push_health = PushHealth.HEALTHY
    task.poll_fallback_armed = True  # keep fallback armed even after rebind
    return task
