# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-bridge-an-mcp-tool-result-into-an-a2a-task-graph-when-the-tool-s-declared-schema-is-satisfiable-but-i.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-bridge-an-mcp-tool-result-into-an-a2a-task-graph-when-the-tool-s-declared-schema-is-satisfiable-but-i.warrant.json
# Markdown SHA-256:   461563119168c11115e64de091f1c843e8ff6151f78c8c70a33adb5c674f868a
# Code AST SHA-256:   fa346bb0181ff03abbbf4521b8a73bfae94253d8bec9552dd41cb7aaa80fc7dd
# Verified Classes:   UnbridgeablePromotionError, McpOutputContract, PromotionDecision
# Defensive Guards:   6 fail-closed invariants (zero external deps)

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


class UnbridgeablePromotionError(RuntimeError):
    """Raised when an MCP tool result cannot be safely promoted to an A2A artifact."""


@dataclass
class McpOutputContract:
    schema_valid: bool
    max_items: Optional[int]          # None means unbounded
    identity_key: Optional[str]       # None means elements are not stably identifiable
    idempotent_reinvocation: bool
    truncation_policy: Optional[str]  # required if max_items is enforced by bridge cap


@dataclass
class PromotionDecision:
    promote: bool
    advisory_only: bool
    metadata: dict[str, Any] = field(default_factory=dict)


def decide_promotion(
    contract: McpOutputContract,
    bridge_cardinality_cap: Optional[int],
    will_be_peer_verified: bool,
    reachable_by_retry: bool,
) -> PromotionDecision:
    if not contract.schema_valid:
        raise UnbridgeablePromotionError("output does not validate; cannot promote")

    effective_bound = contract.max_items if contract.max_items is not None else bridge_cardinality_cap

    # Unbounded cardinality into a durable artifact is never safe.
    if effective_bound is None:
        raise UnbridgeablePromotionError(
            "unbounded cardinality with no bridge cap; demote to advisory"
        )

    # Peer-verified artifacts require stable element identity for replay comparison.
    if will_be_peer_verified and contract.identity_key is None:
        raise UnbridgeablePromotionError(
            "peer-verified artifact lacks declared identity key; replay comparison undefined"
        )

    # Retry-reachable skills require idempotent re-invocation or replay drifts.
    if reachable_by_retry and not contract.idempotent_reinvocation:
        raise UnbridgeablePromotionError(
            "retry-reachable skill is not idempotent; replay cardinality would drift"
        )

    # If the bound is enforced by the bridge rather than the schema, a recorded
    # truncation policy is mandatory so replay truncates identically.
    if contract.max_items is None and contract.truncation_policy is None:
        raise UnbridgeablePromotionError(
            "bridge-enforced cap without recorded truncation policy; replay not reconstructible"
        )

    return PromotionDecision(
        promote=True,
        advisory_only=False,
        metadata={
            "cardinality_bound": effective_bound,
            "identity_key": contract.identity_key,
            "truncation_policy": contract.truncation_policy,
            "idempotent": contract.idempotent_reinvocation,
        },
    )


def bridge_tool_result(
    contract: McpOutputContract,
    payload: list[dict[str, Any]],
    bridge_cardinality_cap: Optional[int],
    will_be_peer_verified: bool,
    reachable_by_retry: bool,
) -> PromotionDecision:
    decision = decide_promotion(
        contract, bridge_cardinality_cap, will_be_peer_verified, reachable_by_retry
    )
    bound = decision.metadata["cardinality_bound"]
    if len(payload) > bound:
        # Deterministic truncation must mirror the recorded policy.
        if contract.identity_key is None:
            raise UnbridgeablePromotionError(
                "cannot truncate deterministically without identity key"
            )
        payload.sort(key=lambda e: e[contract.identity_key])
        del payload[bound:]
    return decision
