# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-lost-task-update-stream-when-an-a2a-v1-0-push-notification-webhook-silently-supersedes-the-sse-channel.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-lost-task-update-stream-when-an-a2a-v1-0-push-notification-webhook-silently-supersedes-the-sse-channel.warrant.json
# Markdown SHA-256:   ad58f017ce8490495ad679f10ea0889c1b7d00bb8f669a3444d59e6827400fea
# Code AST SHA-256:   2adba69ce78bd66c95502bc02d692cd7850f29decd6f2deda367d8211ee93a66
# Verified Classes:   StreamSupersessionUnreconciled, ChannelLiveness
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class StreamSupersessionUnreconciled(RuntimeError):
    """Raised when a stream is suspected superseded by push routing but terminal
    state cannot be recovered from tasks/get within the reconciliation budget."""
    pass


@dataclass
class ChannelLiveness:
    task_id: str
    last_stream_event_ts: float = 0.0      # updated ONLY on Task*UpdateEvent, not keepalives
    last_push_delivery_ts: float = 0.0     # updated by webhook receiver, keyed by task_id
    theta_stream: float = 30.0             # max stream silence before divergence check
    theta_total: float = 120.0             # max total silence before hard escalation
    _reconciled: bool = field(default=False, init=False)


def classify_channel(liv: ChannelLiveness, now: Optional[float] = None) -> str:
    now = now if now is not None else time.monotonic()
    stream_idle = now - liv.last_stream_event_ts
    push_idle = now - liv.last_push_delivery_ts

    if stream_idle <= liv.theta_stream:
        return "stream_authoritative"

    # Stream silent past theta_stream. Is push demonstrably advancing?
    if liv.last_push_delivery_ts > liv.last_stream_event_ts:
        return "stream_superseded_reconcile_via_tasks_get"

    if stream_idle > liv.theta_total and push_idle > liv.theta_total:
        return "double_channel_silence_escalate"

    return "stream_silent_push_also_silent_wait"


async def resolve_terminal_state(liv: ChannelLiveness, tasks_get) -> dict:
    """Drive the task to a terminal state, treating the stream as non-authoritative
    once supersession is detected. tasks_get(task_id) -> dict with 'state'."""
    verdict = classify_channel(liv)

    if verdict == "stream_authoritative":
        # Caller should keep awaiting the stream; nothing to do here.
        return {"action": "await_stream"}

    if verdict in ("stream_superseded_reconcile_via_tasks_get",
                   "stream_silent_push_also_silent_wait",
                   "double_channel_silence_escalate"):
        deadline = time.monotonic() + liv.theta_total
        while time.monotonic() < deadline:
            snap = await tasks_get(liv.task_id)
            if snap.get("state") in ("completed", "failed", "canceled", "rejected"):
                liv._reconciled = True
                return {"action": "terminal_recovered", "state": snap["state"], "snap": snap}
            await _sleep(2.0)
        raise StreamSupersessionUnreconciled(
            f"task {liv.task_id}: stream superseded by push routing (stream_idle="
            f"{time.monotonic() - liv.last_stream_event_ts:.1f}s, verdict={verdict}) "
            f"and tasks/get did not yield terminal state within {liv.theta_total}s"
        )

    raise StreamSupersessionUnreconciled(f"unclassified verdict {verdict!r}")


async def _sleep(s: float) -> None:
    import asyncio
    await asyncio.sleep(s)
