# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-a2a-agent-card-has-gone-stale-across-an-org-boundary-and-why-signature-validity-is-not-freshness.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-a2a-agent-card-has-gone-stale-across-an-org-boundary-and-why-signature-validity-is-not-freshness.warrant.json
# Markdown SHA-256:   fa2817e03c6f221928da313fee31f3c145eec7b049a58a6b97c67b345763c3c6
# Code AST SHA-256:   0f40c937bb333af56058644485b2d651f4d8341f1689b8dc647c0be4565a0494
# Verified Classes:   StaleAgentCardError, SkillDescriptor, AgentCard
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from __future__ import annotations

import hashlib
import json
from dataclasses import dataclass, field


class StaleAgentCardError(RuntimeError):
    """Raised when a signature-valid Agent Card is operationally stale for a delegation."""

    def __init__(self, reason: str, detail: dict):
        super().__init__(f"{reason}: {detail}")
        self.reason = reason
        self.detail = detail


@dataclass
class SkillDescriptor:
    skill_id: str
    version: str
    input_schema_hash: str  # sha256 of canonicalized inputSchema
    output_schema_hash: str


@dataclass
class AgentCard:
    agent_name: str
    signing_kid: str
    skills: dict[str, SkillDescriptor] = field(default_factory=dict)
    scopes: dict[str, str] = field(default_factory=dict)  # scope_name -> resource_descriptor_hash


def _schema_hash(schema: dict) -> str:
    canonical = json.dumps(schema, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode()).hexdigest()


def assert_card_fresh_for_delegation(
    cached: AgentCard,
    live: AgentCard,
    *,
    intended_skill: str,
    intended_scope: str,
) -> None:
    """
    Enforce the cross-org freshness invariant before minting a delegation warrant.

    Aborts on schema-identity violation, scope-subset violation, skill removal,
    or version regression. Tolerates additive optional fields, description drift,
    and new skills.
    """
    # Identity surface must be stable; if it moved, this is not a staleness
    # question — it is a different agent and the cache is simply wrong.
    if (cached.agent_name, cached.signing_kid) != (live.agent_name, live.signing_kid):
        raise StaleAgentCardError(
            "identity_drift",
            {"cached": (cached.agent_name, cached.signing_kid),
             "live": (live.agent_name, live.signing_kid)},
        )

    if intended_skill not in live.skills:
        raise StaleAgentCardError(
            "skill_removed",
            {"skill": intended_skill, "live_skills": sorted(live.skills)},
        )

    c_skill = cached.skills.get(intended_skill)
    l_skill = live.skills[intended_skill]

    if c_skill is not None:
        if _version_lt(l_skill.version, c_skill.version):
            raise StaleAgentCardError(
                "version_regression",
                {"skill": intended_skill,
                 "cached_version": c_skill.version,
                 "live_version": l_skill.version},
            )
        if l_skill.input_schema_hash != c_skill.input_schema_hash:
            raise StaleAgentCardError(
                "input_schema_changed",
                {"skill": intended_skill,
                 "cached_hash": c_skill.input_schema_hash,
                 "live_hash": l_skill.input_schema_hash},
            )
        if l_skill.output_schema_hash != c_skill.output_schema_hash:
            raise StaleAgentCardError(
                "output_schema_changed",
                {"skill": intended_skill,
                 "cached_hash": c_skill.output_schema_hash,
                 "live_hash": l_skill.output_schema_hash},
            )

    # Scope check compares resource descriptors, not names — a renamed scope
    # that still exists with different semantics is the dangerous case.
    if intended_scope not in live.scopes:
        raise StaleAgentCardError(
            "scope_absent_live",
            {"scope": intended_scope, "live_scopes": sorted(live.scopes)},
        )
    if intended_scope in cached.scopes:
        if cached.scopes[intended_scope] != live.scopes[intended_scope]:
            raise StaleAgentCardError(
                "scope_resource_changed",
                {"scope": intended_scope,
                 "cached_resource": cached.scopes[intended_scope],
                 "live_resource": live.scopes[intended_scope]},
            )


def _version_lt(a: str, b: str) -> bool:
    def parse(v: str) -> tuple[int, ...]:
        return tuple(int(p) for p in v.split(".") if p.isdigit())
    return parse(a) < parse(b)


def delegate_with_freshness_gate(
    cached: AgentCard,
    fetch_live_card,
    *,
    intended_skill: str,
    intended_scope: str,
    mint_warrant,
    send_task,
):
    live = fetch_live_card()
    assert_card_fresh_for_delegation(
        cached, live,
        intended_skill=intended_skill,
        intended_scope=intended_scope,
    )
    warrant = mint_warrant(scope=intended_scope, audience=live.agent_name)
    return send_task(warrant=warrant, skill=intended_skill)
