# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-an-a2a-v1-0-tasks-resubscribe-after-a-webhook-binding-has-already-been-pushed-the-push-notification-epoch-gap-and-the-ter.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-an-a2a-v1-0-tasks-resubscribe-after-a-webhook-binding-has-already-been-pushed-the-push-notification-epoch-gap-and-the-ter.warrant.json
# Markdown SHA-256:   614e2af08ed19fafd4934cdb7a4d7bf7636364fe3dce60d82437b94907aaf56d
# Code AST SHA-256:   4e47c1ec04186127ead989c32ada740b55c7d8c51ee3b2a6f41cbc66269c9759
# Verified Classes:   Channel, TaskState, EpochGapError, TerminalResurrectionError, Transition, TaskProjection
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class Channel(str, Enum):
    SSE = "sse"
    WEBHOOK = "webhook"
    GET = "get"


class TaskState(str, Enum):
    SUBMITTED = "submitted"
    WORKING = "working"
    INPUT_REQUIRED = "input-required"
    COMPLETED = "completed"
    FAILED = "failed"
    CANCELED = "canceled"


TERMINAL = {TaskState.COMPLETED, TaskState.FAILED, TaskState.CANCELED}


class EpochGapError(RuntimeError):
    """Raised when an SSE replay cannot cover a webhook config-rotation gap."""


class TerminalResurrectionError(RuntimeError):
    """Raised when an event would move a locally-terminal task to non-terminal."""


@dataclass
class Transition:
    state: TaskState
    timestamp: int
    source: Channel


@dataclass
class TaskProjection:
    task_id: str
    state: TaskState = TaskState.SUBMITTED
    last_timestamp: int = 0
    rotation_ts: int | None = None
    applied: list[Transition] = field(default_factory=list)

    def apply(self, ev: Transition) -> None:
        # Monotone guard: terminal is absorbing regardless of channel.
        if self.state in TERMINAL and ev.state not in TERMINAL:
            raise TerminalResurrectionError(
                f"task {self.task_id}: event {ev.state}@{ev.timestamp} via {ev.source} "
                f"would resurrect terminal state {self.state}"
            )
        # Stale replay: ignore events older than last applied timestamp.
        if ev.timestamp < self.last_timestamp:
            return
        # SSE supersedes webhook for state; webhook only fills liveness.
        if ev.source is Channel.WEBHOOK and ev.state not in TERMINAL:
            # Non-terminal webhook events are liveness signals only; do not
            # let them advance state — SSE is the continuity channel.
            return
        self.state = ev.state
        self.last_timestamp = ev.timestamp
        self.applied.append(ev)

    def record_rotation(self, ts: int) -> None:
        self.rotation_ts = ts


def resubscribe(proj: TaskProjection, replay_start_ts: int, now: int) -> None:
    """Open SSE continuity stream; refuse if rotation gap is unrecoverable."""
    if proj.state in TERMINAL:
        # Do not resubscribe on a terminal task with a live webhook.
        raise TerminalResurrectionError(
            f"task {proj.task_id}: refusing resubscribe on terminal {proj.state}"
        )
    if proj.rotation_ts is not None and replay_start_ts > proj.rotation_ts:
        raise EpochGapError(
            f"task {proj.task_id}: SSE replay starts at {replay_start_ts} but webhook "
            f"rotated at {proj.rotation_ts}; gap unrecoverable, reconcile via tasks/get"
        )
    # Otherwise: stream is authoritative for gap-filling; caller applies events
    # with source=Channel.SSE and the projection supersedes webhook state.
