# 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-discovery-when-the-remote-task-lifecycle-has-already-advanced-past-the-advertised-capab.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-agent-card-during-a2a-v1-0-discovery-when-the-remote-task-lifecycle-has-already-advanced-past-the-advertised-capab.warrant.json
# Markdown SHA-256:   13895656d0f146ea747f0ce72d9523db4b7f407ded133d2658c6e0ce47d31a1a
# Code AST SHA-256:   91fe40deebe0eae7b7c75640d61829feadee3fc9d3d342f846bdd1d024eb605a
# Verified Classes:   StaleAgentCardBindingError, SkillConstraint, AgentCard
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleAgentCardBindingError(RuntimeError):
    """Raised when a push-notification binding was made against a card
    whose advertised constraints cannot support the binding's liveness
    deadline, or when the card has drifted since binding."""
    pass


@dataclass
class SkillConstraint:
    skill_id: str
    max_concurrent_tasks: int
    p99_latency_s: float


@dataclass
class AgentCard:
    version: str
    push_notifications: bool
    skills: dict[str, SkillConstraint]


def derive_binding_deadline(card: AgentCard, skill_id: str,
                            observed_queue_depth: int,
                            dispatch_grace_s: float = 60.0) -> float:
    if not card.push_notifications:
        raise StaleAgentCardBindingError(
            f"card {card.version} does not advertise pushNotifications; "
            f"cannot bind a webhook for skill {skill_id}")
    skill = card.skills.get(skill_id)
    if skill is None:
        raise StaleAgentCardBindingError(
            f"skill {skill_id} absent from card {card.version}")
    if observed_queue_depth >= skill.max_concurrent_tasks:
        # Queue exceeds the advertised slot count: the binding will sit
        # behind the gate and may never fire within any sane watchdog.
        raise StaleAgentCardBindingError(
            f"queue depth {observed_queue_depth} >= maxConcurrentTasks "
            f"{skill.max_concurrent_tasks} for skill {skill_id}; "
            f"binding would be silently dead")
    return (observed_queue_depth * skill.p99_latency_s) + dispatch_grace_s


def assert_binding_liveness(card: AgentCard, skill_id: str,
                            observed_queue_depth: int,
                            watchdog_timeout_s: float) -> float:
    deadline = derive_binding_deadline(card, skill_id, observed_queue_depth)
    if watchdog_timeout_s >= deadline:
        raise StaleAgentCardBindingError(
            f"watchdog {watchdog_timeout_s}s >= derived deadline "
            f"{deadline:.1f}s for skill {skill_id}; push loss would be "
            f"unbounded — fall back to polling before submitting")
    return deadline


def check_card_drift(pre: AgentCard, post: AgentCard,
                     skill_id: str) -> None:
    if pre.version == post.version and pre.skills.keys() == post.skills.keys():
        return
    if skill_id not in post.skills:
        raise StaleAgentCardBindingError(
            f"skill {skill_id} retired between card {pre.version} and "
            f"{post.version}; existing binding is stale")
    if not post.push_notifications:
        raise StaleAgentCardBindingError(
            f"pushNotifications disabled in card {post.version}; "
            f"binding must be renegotiated")
