# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-emit-a-genai-span-when-tool-call-attribution-cannot-be-reconstructed-from-the-parent-context.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-emit-a-genai-span-when-tool-call-attribution-cannot-be-reconstructed-from-the-parent-context.warrant.json
# Markdown SHA-256:   43f7cc05836dd1337dfd5d1152dc7e68f265059bc6ee321bc1f504963e284e9b
# Code AST SHA-256:   67cd97820a71770274536b89f145d3a101314707ef23c89bd37b3daafef67766
# Verified Classes:   GenAIAttributionError, DispatchRecord, ExecutionContext
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class GenAIAttributionError(RuntimeError):
    """Raised when a tool-call span cannot be causally attributed to its requesting gen_ai span."""


@dataclass(frozen=True)
class DispatchRecord:
    trace_id: str
    parent_span_id: str
    tool_name: str
    args_digest: str


@dataclass(frozen=True)
class ExecutionContext:
    trace_id: str
    parent_span_id: str
    tool_name: str
    args: dict
    parent_operation_name: str | None  # None => no resolvable parent
    ambient_span_id: str | None        # pool-worker residue; must NOT be trusted


GENAI_REASONING_OPS = {"chat", "invoke_agent", "execute_tool"}


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


def resolve_attribution(dispatch: DispatchRecord, ctx: ExecutionContext) -> str:
    # Fail closed: no parent means no attributed child, ever.
    if not ctx.parent_span_id or ctx.parent_span_id == "0" * 16:
        raise GenAIAttributionError(
            f"tool {ctx.tool_name!r} has no parent_span_id; refusing to invent a root"
        )

    # Context bleed: parent resolves into a different trace than the requester claimed.
    if ctx.trace_id != dispatch.trace_id:
        raise GenAIAttributionError(
            f"trace mismatch: dispatch={dispatch.trace_id} exec={ctx.trace_id}; "
            f"ambient_span={ctx.ambient_span_id} must not be used as parent"
        )

    # Parent exists but is not a gen_ai reasoning operation -> structural lie.
    if ctx.parent_operation_name not in GENAI_REASONING_OPS:
        raise GenAIAttributionError(
            f"parent op {ctx.parent_operation_name!r} is not a gen_ai reasoning op; "
            "degraded emit required, not attributed child"
        )

    # Stale replay: same span IDs, different arguments.
    if digest_args(ctx.args) != dispatch.args_digest:
        raise GenAIAttributionError(
            f"args_digest mismatch for tool {ctx.tool_name!r}: "
            "replayed dispatch with mutated inputs; emit degraded, do not attribute"
        )

    return "attributed"


def emit_tool_span(dispatch: DispatchRecord, ctx: ExecutionContext) -> dict:
    try:
        attribution = resolve_attribution(dispatch, ctx)
    except GenAIAttributionError as exc:
        # Degraded path: emit a root span with explicit unresolved attribution.
        return {
            "span_name": f"gen_ai.tool.call {ctx.tool_name}",
            "parent_span_id": None,
            "gen_ai.tool.call.attribution": "unresolved",
            "attribution.reason": str(exc),
        }
    return {
        "span_name": f"gen_ai.tool.call {ctx.tool_name}",
        "parent_span_id": ctx.parent_span_id,
        "gen_ai.tool.call.attribution": attribution,
        "gen_ai.tool.name": ctx.tool_name,
    }
