# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-delegated-a2a-warrants-that-resolve-to-an-mcp-capability-alias-it-already-holds-locally.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-delegated-a2a-warrants-that-resolve-to-an-mcp-capability-alias-it-already-holds-locally.warrant.json
# Markdown SHA-256:   e04d797a3530be5825e6c8193d8f80132d1f1c9ded6fe99b6e1524e7f197402a
# Code AST SHA-256:   a5da5c12cfccd2f1f1afd6cb9758d9ed2f3ee9bcfe77e1c8a749a39153df29e0
# Verified Classes:   AliasCollisionError, Descriptor, Warrant
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class AliasCollisionError(RuntimeError):
    """Raised when a delegated A2A warrant's capability descriptor does not
    match the callee's local MCP descriptor for the same alias."""
    pass


@dataclass(frozen=True)
class Descriptor:
    name: str
    scope: str          # "ro" | "rw"
    endpoint: str
    schema: str

    def canonical_hash(self) -> str:
        payload = json.dumps(
            {"name": self.name, "scope": self.scope,
             "endpoint": self.endpoint, "schema": self.schema},
            sort_keys=True, separators=(",", ":"),
        ).encode("utf-8")
        return hashlib.sha256(payload).hexdigest()


@dataclass(frozen=True)
class Warrant:
    warrant_id: str
    issuer: str
    descriptor: Descriptor
    issued_at: int
    expiry: int


def resolve_delegated_warrant(
    warrant: Warrant,
    local_registry: dict[str, Descriptor],
    last_seen_issued_at: dict[str, int],
    now: int,
) -> Descriptor:
    if now >= warrant.expiry:
        raise AliasCollisionError(
            f"warrant {warrant.warrant_id} expired at {warrant.expiry}, now={now}"
        )

    prev = last_seen_issued_at.get(warrant.issuer, -1)
    if warrant.issued_at <= prev:
        raise AliasCollisionError(
            f"monotonicity violation for issuer {warrant.issuer}: "
            f"issued_at={warrant.issued_at} <= last_seen={prev}"
        )

    local = local_registry.get(warrant.descriptor.name)
    if local is None:
        raise AliasCollisionError(
            f"alias {warrant.descriptor.name!r} present in issuer descriptor "
            f"but absent from local MCP registry; refusing to no-op"
        )

    h_issuer = warrant.descriptor.canonical_hash()
    h_local = local.canonical_hash()
    if h_issuer != h_local:
        raise AliasCollisionError(
            f"alias collision on {warrant.descriptor.name!r}: "
            f"H_issuer={h_issuer} H_local={h_local} "
            f"issuer_scope={warrant.descriptor.scope} "
            f"local_scope={local.scope} "
            f"issuer_endpoint={warrant.descriptor.endpoint} "
            f"local_endpoint={local.endpoint}"
        )

    return local
