# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a2a-v1-0-agent-card-capability-declarations-against-task-lifecycle-terminal-states-when-a-push-notification-webhook-i.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a2a-v1-0-agent-card-capability-declarations-against-task-lifecycle-terminal-states-when-a-push-notification-webhook-i.warrant.json
# Markdown SHA-256:   f813462ae77b6c6fe4d28ee2d485617cb56739641146f42af7bcb47b637b3060
# Code AST SHA-256:   fca65c6e3c8a368ca371628b94a3ff2846c39eb153bcf07f5d2269d25c5277f2
# Verified Classes:   PushDeliveryContractError, TaskState, AgentCard, Task
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class PushDeliveryContractError(RuntimeError):
    """Raised when a task's terminal state cannot be reconciled with push delivery."""
    pass


class TaskState(Enum):
    SUBMITTED = "submitted"
    WORKING = "working"
    COMPLETED = "completed"
    FAILED = "failed"
    AWAITING_WEBHOOK = "awaiting_webhook"  # client-local, not an A2A state


@dataclass
class AgentCard:
    push_notifications: bool
    streaming: bool
    observed_deliveries: int = 0
    observed_tasks: int = 0

    def push_is_advisory(self) -> bool:
        # Card claims push, but we have never seen a delivery land.
        return self.push_notifications and self.observed_deliveries == 0


@dataclass
class Task:
    id: str
    state: TaskState
    push_config_registered_at: Optional[float] = None
    first_non_submitted_at: Optional[float] = None
    deadline: float = 0.0
    result: Optional[str] = None


def reconcile(card: AgentCard, task: Task, now: float,
              poll_get, webhook_fired: bool) -> TaskState:
    """
    Enforce: tasks/get owns terminal state; webhook is advisory.
    Bounded await; on deadline, force reconciliation.
    """
    if webhook_fired:
        card.observed_deliveries += 1
        card.observed_tasks += 1
        return TaskState.COMPLETED

    # Registration race: config landed after first transition.
    if (task.push_config_registered_at is not None
            and task.first_non_submitted_at is not None
            and task.push_config_registered_at > task.first_non_submitted_at):
        # Webhook will never fire for this task; do not wait.
        pass

    if now < task.deadline and not card.push_is_advisory():
        return TaskState.AWAITING_WEBHOOK

    # Deadline reached, or push is advisory: reconcile via tasks/get.
    remote = poll_get(task.id)
    if remote["state"] in ("completed", "failed"):
        card.observed_tasks += 1
        task.result = remote.get("result")
        return TaskState(remote["state"])

    if now >= task.deadline:
        raise PushDeliveryContractError(
            f"task {task.id}: deadline {task.deadline} passed, "
            f"tasks/get still reports {remote['state']!r}, "
            f"push_notifications={card.push_notifications}, "
            f"observed_deliveries={card.observed_deliveries}"
        )
    return TaskState.AWAITING_WEBHOOK
