# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-resolves-a-stale-a2a-agent-card-against-a-live-task-lifecycle-the-cardversion-taskstate-skew-and-the-orphaned-push-callb.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-resolves-a-stale-a2a-agent-card-against-a-live-task-lifecycle-the-cardversion-taskstate-skew-and-the-orphaned-push-callb.warrant.json
# Markdown SHA-256:   29e299c430aa067ad79f49a2473bfc7f43f5726ed153c65594f9e8814c3d6dd2
# Code AST SHA-256:   7ea72c0429cce490ea16c427346b2ab8a809ffaa5e197f967911649a2bc701a8
# Verified Classes:   CardSkewDeadlock, AgentCard, PushNotification, TaskRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class CardSkewDeadlock(RuntimeError):
    """Raised when a push notification arrives under a card version the
    client cannot reconcile, and the client has no resync path. This is the
    exact condition that produces silent bilateral deadlock."""


@dataclass
class AgentCard:
    version: str
    push_signing_kids: set[str]
    transition_graph: dict[str, set[str]]


@dataclass
class PushNotification:
    task_id: str
    card_version: str
    target_state: str
    signature_kid: str
    received_at: float = field(default_factory=time.time)


class TaskRecord:
    def __init__(self, task_id: str, state: str = "working"):
        self.task_id = task_id
        self.state = state
        self.last_remote_ttl: Optional[float] = None


def handle_push(
    record: TaskRecord,
    note: PushNotification,
    cached_card: AgentCard,
    fetch_card,
) -> str:
    # Case 1: versions agree -> normal processing.
    if note.card_version == cached_card.version:
        if note.target_state not in cached_card.transition_graph.get(record.state, set()):
            raise CardSkewDeadlock(
                f"same-version transition {record.state}->{note.target_state} "
                f"not in graph for task {record.task_id}"
            )
        record.state = note.target_state
        return "processed"

    # Case 2: version skew. Do NOT drop. Resync.
    fresh = fetch_card()
    if note.signature_kid not in fresh.push_signing_kids:
        # Even after resync the key is unknown: this is a genuine auth
        # failure, but it must be surfaced, not silently dropped.
        raise CardSkewDeadlock(
            f"kid {note.signature_kid} unknown after resync for task "
            f"{record.task_id}; cached={cached_card.version} fresh={fresh.version}"
        )

    # Signature valid against fresh key set; now replay against fresh graph.
    if note.target_state not in fresh.transition_graph.get(record.state, set()):
        # The fresh graph still doesn't permit the transition. This means the
        # client's local state was itself stale. Force-reconcile from remote.
        raise CardSkewDeadlock(
            f"post-resync transition {record.state}->{note.target_state} "
            f"still invalid for task {record.task_id}; manual reconcile required"
        )

    record.state = note.target_state
    cached_card.version = fresh.version
    cached_card.push_signing_kids = fresh.push_signing_kids
    cached_card.transition_graph = fresh.transition_graph
    return "processed_after_resync"


def reconcile_orphans(records: list[TaskRecord], now: float, get_remote_state) -> None:
    for r in records:
        if r.state in ("working", "auth-required", "input-required") and r.last_remote_ttl and now > r.last_remote_ttl:
            remote_state = get_remote_state(r.task_id)
            if remote_state != r.state:
                r.state = remote_state
                # Log as continuity event; do not raise, but never silently skip.
                print(f"continuity: task {r.task_id} reconciled {r.state}->{remote_state}")
