# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-reject-a-valid-a2a-v1-0-push-notification-webhook-after-task-resurrection-the-taskid-vs-contextid-reattachment-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-reject-a-valid-a2a-v1-0-push-notification-webhook-after-task-resurrection-the-taskid-vs-contextid-reattachment-invariant.warrant.json
# Markdown SHA-256:   bc6f4e77263508413811533495e81a83b85a417aa37a93cd8d1203e4fd013dad
# Code AST SHA-256:   63e22626528474db8fd065a02760873151a82e28f602f08e1353c5aff91b1644
# Verified Classes:   PushConfigAffinityError, PushConfig, TaskRecord, Dispatcher
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Literal


class PushConfigAffinityError(RuntimeError):
    """Raised when a push-notification config cannot be bound to a stable task identity."""


@dataclass(frozen=True)
class PushConfig:
    config_id: str
    task_id: str | None
    context_id: str
    url: str


@dataclass
class TaskRecord:
    task_id: str
    context_id: str
    state: Literal["submitted", "working", "input-required", "completed", "failed", "canceled"]


@dataclass
class Dispatcher:
    tasks: dict[str, TaskRecord] = field(default_factory=dict)
    configs_by_task: dict[str, list[PushConfig]] = field(default_factory=dict)
    configs_by_context: dict[str, list[PushConfig]] = field(default_factory=dict)

    def register(self, cfg: PushConfig) -> None:
        # Guardrail: refuse context-only registration when the task is known.
        if cfg.task_id is None:
            owners = [t for t in self.tasks.values() if t.context_id == cfg.context_id]
            if len(owners) != 1:
                raise PushConfigAffinityError(
                    f"context {cfg.context_id!r} does not resolve to exactly one task; "
                    f"refusing context-scoped push config {cfg.config_id!r}"
                )
            cfg = PushConfig(cfg.config_id, owners[0].task_id, cfg.context_id, cfg.url)
        task = self.tasks.get(cfg.task_id)
        if task is None:
            raise PushConfigAffinityError(f"unknown task {cfg.task_id!r}")
        if task.context_id != cfg.context_id:
            # Client is trying to attach a notification to a task under a stale context.
            raise PushConfigAffinityError(
                f"config {cfg.config_id!r} context {cfg.context_id!r} != task "
                f"{cfg.task_id!r} current context {task.context_id!r}"
            )
        self.configs_by_task.setdefault(cfg.task_id, []).append(cfg)
        self.configs_by_context.setdefault(cfg.context_id, []).append(cfg)

    def dispatch(self, task_id: str) -> list[PushConfig]:
        # Guardrail: resolution is task-scoped. Context is never the primary key.
        task = self.tasks.get(task_id)
        if task is None:
            raise PushConfigAffinityError(f"dispatch for unknown task {task_id!r}")
        configs = self.configs_by_task.get(task_id, [])
        if not configs:
            raise PushConfigAffinityError(
                f"task {task_id!r} has no bound push config; "
                f"event would be silently dropped (context {task.context_id!r})"
            )
        return [c for c in configs if c.context_id == task.context_id] or configs
