# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-federated-aaif-token-whose-aud-chain-is-valid-but-whose-act-chain-forks.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-federated-aaif-token-whose-aud-chain-is-valid-but-whose-act-chain-forks.warrant.json
# Markdown SHA-256:   edeff5b6c720bde1500e111a0caa73b2758b5fd15aafc56270253fcd2b33ee1c
# Code AST SHA-256:   e3e292d291569a8a3b7abe14d7c42aa475326c7a69ff525a6ba0b3a115591550
# Verified Classes:   ForkedActorChainError, ActNode
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ForkedActorChainError(RuntimeError):
    """Raised when an AAIF token's act chain has a multi-parent node at a side-effect boundary."""
    pass


@dataclass
class ActNode:
    sub: str
    parents: tuple[str, ...] = ()


def walk_act_chain(act: dict) -> list[ActNode]:
    """Flatten a nested act structure into (sub, parents) nodes.

    Handles both the linear `{sub, act: {...}}` form and the forked
    `{sub, act: [{...}, {...}]}` form the gateway produced.
    """
    nodes: list[ActNode] = []

    def _walk(node: dict, parent_sub: Optional[str]) -> None:
        sub = node.get("sub")
        if not sub:
            raise ForkedActorChainError("act node missing sub; cannot attribute")
        parents = (parent_sub,) if parent_sub else ()
        nodes.append(ActNode(sub=sub, parents=parents))
        child = node.get("act")
        if child is None:
            return
        if isinstance(child, dict):
            _walk(child, sub)
        elif isinstance(child, list):
            for c in child:
                _walk(c, sub)
        else:
            raise ForkedActorChainError(f"unrecognized act shape at {sub}")

    _walk(act, None)
    return nodes


def assert_path_shaped_act_chain(
    act: dict,
    *,
    side_effecting: bool,
    requires_unique_ancestral_attribution: bool,
) -> str:
    """Enforce the continuity invariant and return the attributable principal.

    Raises ForkedActorChainError when the act chain forks at a boundary that
    requires a single ancestral principal. Returns the leaf sub otherwise.
    """
    nodes = walk_act_chain(act)

    # Degree of each node as a *child* of some parent.
    degree: dict[str, int] = {}
    for n in nodes:
        for p in n.parents:
            degree[p] = degree.get(p, 0) + 1

    forked = [sub for sub, d in degree.items() if d > 1]

    if forked and side_effecting and requires_unique_ancestral_attribution:
        raise ForkedActorChainError(
            "act chain forks at %r; refusing side effect because ancestral "
            "attribution is ambiguous. Mint one token per downstream "
            "capability instead of unioning audiences." % (forked,)
        )

    # Leaf is always unambiguous even when ancestors fork.
    leaf = nodes[-1].sub
    return leaf


def handle_tools_call(token_act: dict, tool_name: str, mutates_state: bool) -> str:
    """Entry point at the MCP tools/call boundary."""
    principal = assert_path_shaped_act_chain(
        token_act,
        side_effecting=mutates_state,
        requires_unique_ancestral_attribution=mutates_state,
    )
    return principal
