# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-silently-orphan-an-a2a-task-when-the-remote-agent-card-s-capabilities-pushnotifications-flag-flips-between-discovery-and-the-firs.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-silently-orphan-an-a2a-task-when-the-remote-agent-card-s-capabilities-pushnotifications-flag-flips-between-discovery-and-the-firs.warrant.json
# Markdown SHA-256:   addd3a10d2262cb05c9803e870d0c5a19587ba07e8f8ff7d32c8ce4df01e0686
# Code AST SHA-256:   f8d1460f91f776faba7919a0fc4c1e84141b74794d1566adda0fa62cb37f00e3
# Verified Classes:   PushSubscriptionNotGranted, TaskOrphaned, AgentCard, PushConfig, SetResponse, LocalTask
# Defensive Guards:   6 fail-closed invariants (zero external deps)

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


class PushSubscriptionNotGranted(RuntimeError):
    """Raised when a pushNotificationConfig/set response does not constitute a verified grant."""
    pass


class TaskOrphaned(RuntimeError):
    """Raised when a task is in a webhook-dependent state without a verified subscription."""
    pass


@dataclass
class AgentCard:
    push_notifications: bool
    fetched_at: float


@dataclass
class PushConfig:
    url: str
    token: Optional[str]


@dataclass
class SetResponse:
    http_status: int
    returned_url: str
    returned_token: Optional[str]
    config_present: bool


@dataclass
class LocalTask:
    task_id: str
    state: str = "submitted"
    subscription_verified: bool = False
    webhook_timer_armed_at: Optional[float] = None
    last_webhook_receipt: Optional[float] = None


def register_push_subscription(
    card: AgentCard,
    submitted: PushConfig,
    response: SetResponse,
    card_max_age_s: float = 60.0,
) -> None:
    # Re-validate the specific capability field at set-time, not at discovery-time.
    if not card.push_notifications:
        raise PushSubscriptionNotGranted(
            "Card reports pushNotifications=false at set-time; fall back to polling."
        )
    if (time.time() - card.fetched_at) > card_max_age_s:
        raise PushSubscriptionNotGranted(
            "Card capability is stale; re-fetch before attempting subscription."
        )
    # A 200 is not a grant. Validate the returned config structurally.
    if response.http_status != 200 or not response.config_present:
        raise PushSubscriptionNotGranted(
            f"set returned status={response.http_status} config_present={response.config_present}"
        )
    if response.returned_url != submitted.url:
        raise PushSubscriptionNotGranted(
            f"set normalized url {submitted.url!r} -> {response.returned_url!r}; "
            "dispatcher did not accept the submitted endpoint."
        )
    if submitted.token is not None and response.returned_token != submitted.token:
        raise PushSubscriptionNotGranted(
            "set did not round-trip the subscription token; grant is unverified."
        )


def enter_webhook_wait(task: LocalTask, card: AgentCard, submitted: PushConfig,
                       response: SetResponse) -> None:
    register_push_subscription(card, submitted, response)
    task.subscription_verified = True
    task.state = "working"
    task.webhook_timer_armed_at = time.time()


def reconcile(task: LocalTask, now: float, webhook_timeout_s: float = 300.0) -> str:
    # A task in working with no verified subscription is an orphan, not a wait.
    if task.state == "working" and not task.subscription_verified:
        raise TaskOrphaned(
            f"task {task.task_id} in working without verified push subscription; "
            "poll tasks/get to recover terminal state."
        )
    if (task.subscription_verified and task.webhook_timer_armed_at is not None
            and task.last_webhook_receipt is None
            and (now - task.webhook_timer_armed_at) > webhook_timeout_s):
        return "poll_fallback"
    return "ok"
