# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-in-a2a-v1-0-lose-task-state-when-a-push-notification-webhook-re-enters-the-task-lifecycle-after-the-agent-card-s-capabilities-pus.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-in-a2a-v1-0-lose-task-state-when-a-push-notification-webhook-re-enters-the-task-lifecycle-after-the-agent-card-s-capabilities-pus.warrant.json
# Markdown SHA-256:   a200b00506551e73016519dadfcfcfc9fd03d6d53a43449e61bde4318b7dc2fa
# Code AST SHA-256:   2a0fe5419697aa4da138d714c1a1049dcc04bee90768396b66eb45cb706d0476
# Verified Classes:   PushConfigOrphanedError, TaskState, TaskView, ClientPushRegistration, ServingAgent
# 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 PushConfigOrphanedError(RuntimeError):
    """Raised when a client's registered push config generation no longer
    matches the serving agent's current generation for a non-terminal task."""
    pass


class TaskState(Enum):
    SUBMITTED = "submitted"
    WORKING = "working"
    COMPLETED = "completed"
    FAILED = "failed"
    CANCELED = "canceled"


@dataclass
class TaskView:
    task_id: str
    state: TaskState
    push_config_generation: int  # the field A2A v1.0 is missing


@dataclass
class ClientPushRegistration:
    task_id: str
    url: str
    token: str
    generation: int


@dataclass
class ServingAgent:
    tasks: dict = field(default_factory=dict)          # task_id -> TaskView
    configs: dict = field(default_factory=dict)        # task_id -> (url, token, gen)

    def register_push(self, task_id: str, url: str, token: str) -> int:
        task = self.tasks[task_id]
        if task.state in (TaskState.COMPLETED, TaskState.FAILED, TaskState.CANCELED):
            raise PushConfigOrphanedError(
                f"cannot mutate push config for terminal task {task_id}"
            )
        gen = task.push_config_generation + 1
        task.push_config_generation = gen
        self.configs[task_id] = (url, token, gen)
        return gen

    def admin_rotate(self, task_id: str, new_url: str, new_token: str) -> None:
        # The dangerous path: server-side mutation with no client notification.
        task = self.tasks[task_id]
        if task.state == TaskState.WORKING:
            gen = task.push_config_generation + 1
            task.push_config_generation = gen
            self.configs[task_id] = (new_url, new_token, gen)


def reconcile(client_reg: ClientPushRegistration, agent: ServingAgent) -> None:
    """Client-side guardrail: detect orphaned push config before declaring task lost."""
    task = agent.tasks.get(client_reg.task_id)
    if task is None:
        raise PushConfigOrphanedError(f"task {client_reg.task_id} not found on agent")
    if task.state in (TaskState.COMPLETED, TaskState.FAILED, TaskState.CANCELED):
        return  # terminal: push config is moot, no orphan possible
    if task.push_config_generation != client_reg.generation:
        raise PushConfigOrphanedError(
            f"push config for {client_reg.task_id} is orphaned: "
            f"client registered generation {client_reg.generation}, "
            f"agent is at generation {task.push_config_generation}; "
            f"re-register before trusting push silence as task stall"
        )


if __name__ == "__main__":
    agent = ServingAgent()
    agent.tasks["T1"] = TaskView("T1", TaskState.WORKING, push_config_generation=0)
    gen = agent.register_push("T1", "https://c.example/hook/v1", "tok_a")
    client = ClientPushRegistration("T1", "https://c.example/hook/v1", "tok_a", gen)

    reconcile(client, agent)  # passes: generations match

    agent.admin_rotate("T1", "https://c.example/hook/v2", "tok_b")
    try:
        reconcile(client, agent)
    except PushConfigOrphanedError as e:
        print(f"detected: {e}")
        # recovery: re-register under the new generation
        new_gen = agent.register_push("T1", "https://c.example/hook/v2", "tok_b")
        client = ClientPushRegistration("T1", "https://c.example/hook/v2", "tok_b", new_gen)
        reconcile(client, agent)
        print("reconciled: client is current again")
