# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-capability-warrant-desynchronization-when-an-mcp-gateway-translates-a2a-task-delegation-into-legacy-tool-call-frames.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-capability-warrant-desynchronization-when-an-mcp-gateway-translates-a2a-task-delegation-into-legacy-tool-call-frames.warrant.json
# Markdown SHA-256:   e759e6abb1e4a2b5e619f894e2e088dd710e6ed63e1dd4be9e219f0639ffaf4c
# Code AST SHA-256:   a082b6d0ae66c3c572aef0ce35ba98893470b7696261a75ec4886b0e06479c68
# Verified Classes:   AuthorityDesyncError, A2AGrant, LegacyFrame
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from fnmatch import fnmatch
from typing import Any


class AuthorityDesyncError(RuntimeError):
    """Raised when an A2A grant cannot be preserved in a legacy tool-call frame."""


@dataclass
class A2AGrant:
    capabilities: list[str]          # e.g. ["fs.read:/repo/docs/**"]
    deadline_seconds: float | None
    delegation_chain: list[str]


@dataclass
class LegacyFrame:
    name: str
    arguments: dict[str, Any]
    injected: dict[str, Any] = field(default_factory=dict)  # gateway-enforced bounds


def _glob_within(arg_path: str, grant_globs: list[str]) -> bool:
    return any(fnmatch(arg_path, g) for g in grant_globs)


def translate(
    grant: A2AGrant,
    mcp_tool: str,
    mcp_schema_constrained: bool,
    arguments: dict[str, Any],
    gateway_can_enforce_deadline: bool,
) -> LegacyFrame:
    # 1. Argument-domain check: every fs path argument must sit inside a grant glob.
    for key, val in arguments.items():
        if key == "path" and isinstance(val, str):
            read_grants = [c.split(":", 1)[1] for c in grant.capabilities
                           if c.startswith("fs.read:")]
            if not read_grants:
                raise AuthorityDesyncError(
                    f"argument '{key}' present but grant carries no fs.read capability")
            if not _glob_within(val, read_grants):
                raise AuthorityDesyncError(
                    f"argument '{key}'={val!r} escapes grant globs {read_grants}")

    # 2. Unconstrained schema + prose/unverifiable grant => cannot verify, refuse.
    if not mcp_schema_constrained and not grant.capabilities:
        raise AuthorityDesyncError(
            "unconstrained MCP schema with empty grant: authority unverifiable")

    # 3. Deadline has no legacy slot; must be wrapped or refused.
    injected: dict[str, Any] = {}
    if grant.deadline_seconds is not None:
        if not gateway_can_enforce_deadline:
            raise AuthorityDesyncError(
                "grant carries deadline but gateway cannot wrap it; "
                "emitting frame would evaporate the bound")
        injected["_gateway_deadline_s"] = grant.deadline_seconds

    # 4. Delegation chain has no legacy slot; re-attach out-of-band or refuse.
    if grant.delegation_chain:
        injected["_delegation_chain"] = list(grant.delegation_chain)

    # 5. Authority-surface diff must be empty after wrapping.
    unwrapped = [
        f for f in ("capabilities", "deadline_seconds", "delegation_chain")
        if getattr(grant, f) and f not in ("capabilities",)  # capabilities checked above
        and not any(k.endswith(f) or f in k for k in injected)
    ]
    if unwrapped:
        raise AuthorityDesyncError(
            f"unwrapped authority fields {unwrapped}: refusing translation")

    return LegacyFrame(name=mcp_tool, arguments=arguments, injected=injected)
