# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-agent-card-during-a2a-v1-0-task-resubscription-without-triggering-a-duplicate-task.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-agent-card-during-a2a-v1-0-task-resubscription-without-triggering-a-duplicate-task.warrant.json
# Markdown SHA-256:   ff6f320598a63ab8eb8ef468562d219154443992667c3d158285ae5ecf911669
# Code AST SHA-256:   89a5deb180065900f3ef5360ca2d37d1216da4aff1b708db9dc73ab9b96e2b34
# Verified Classes:   ResubscriptionInvariantError, AgentCard, TaskHandle
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class ResubscriptionInvariantError(RuntimeError):
    """Raised when a resubscription cannot be proven safe under A2A v1.0."""
    pass


@dataclass
class AgentCard:
    version: str
    endpoint: str
    resubscribe_supported: bool
    retention_seconds: int


@dataclass
class TaskHandle:
    task_id: str
    created_at_monotonic: float
    original_endpoint: str
    idempotency_key: str | None


def resubscribe_guard(
    card: AgentCard,
    task: TaskHandle,
    now_monotonic: float,
    server_returned_not_found: bool,
) -> str:
    """
    Decide whether resubscription or resend is safe.
    Returns 'resubscribe' | 'resend_safe' | 'escalate'.
    """
    if card.endpoint != task.original_endpoint:
        # New card governs new tasks only; old task is orphaned on old endpoint.
        raise ResubscriptionInvariantError(
            f"card endpoint {card.endpoint!r} != task endpoint "
            f"{task.original_endpoint!r}; resubscription invalid"
        )

    if not card.resubscribe_supported:
        raise ResubscriptionInvariantError(
            "fresh card no longer advertises tasks/resubscribe"
        )

    age = now_monotonic - task.created_at_monotonic
    expired = age >= card.retention_seconds

    if not server_returned_not_found:
        return "resubscribe"

    if expired:
        return "resend_safe"

    # 404 inside the retention window: server-side invariant breach.
    if task.idempotency_key is None:
        raise ResubscriptionInvariantError(
            f"task {task.task_id!r} 404'd at age {age:.0f}s inside "
            f"retention {card.retention_seconds}s with no idempotency key; "
            "resend would duplicate execution"
        )
    return "escalate"
