# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-span-attribute-truncation-and-orphaned-tool-call-parents-in-opentelemetry-genai-agent-traces.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-span-attribute-truncation-and-orphaned-tool-call-parents-in-opentelemetry-genai-agent-traces.warrant.json
# Markdown SHA-256:   10c659317ce205f82fefac8e5f59f029ba2ee36c948a49a989909b151cc471dd
# Code AST SHA-256:   6b9a84e1e82c9c831db23709eee7b9aa1001ad0779b6ffdaaa3ff926612fb841
# Verified Classes:   TraceReconstructionError, ExportedToolSpan
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import json
from dataclasses import dataclass


class TraceReconstructionError(RuntimeError):
    """Raised when a trace attribute cannot be proven complete for reconstruction."""
    pass


# Backend-configured attribute value cap (bytes). Must match the collector policy.
ATTRIBUTE_VALUE_CAP = 4096


@dataclass
class ExportedToolSpan:
    call_id: str
    arguments: str          # raw exported attribute value
    result: str             # raw exported attribute value


def _looks_truncated(value: str, cap: int) -> bool:
    """A value is suspect if it hits the cap and does not end in a valid
    structural terminator for its format (here: JSON object/array close)."""
    if len(value.encode("utf-8")) < cap:
        return False
    stripped = value.rstrip()
    return not (stripped.endswith("}") or stripped.endswith("]"))


def verify_span_complete(span: ExportedToolSpan, cap: int = ATTRIBUTE_VALUE_CAP) -> None:
    if _looks_truncated(span.arguments, cap):
        raise TraceReconstructionError(
            f"tool call {span.call_id!r}: gen_ai.tool.call.arguments hit cap "
            f"{cap} without structural terminator; value is truncated and "
            f"must not be parsed for reconstruction"
        )
    if _looks_truncated(span.result, cap):
        raise TraceReconstructionError(
            f"tool call {span.call_id!r}: gen_ai.tool.call.result truncated "
            f"at cap {cap}; tool outcome unknown, query side-effect ledger"
        )
    # Only now is it safe to parse.
    try:
        json.loads(span.arguments)
    except json.JSONDecodeError as exc:
        raise TraceReconstructionError(
            f"tool call {span.call_id!r}: arguments failed structural parse "
            f"despite terminator check ({exc}); treat as corrupt"
        ) from exc


def reconstruct_tool_history(
    assistant_tool_call_ids: list[str],
    exported_spans: list[ExportedToolSpan],
) -> dict[str, str]:
    """Join assistant-referenced call IDs against exported child spans.
    Any referenced ID with no child span is 'unknown', never 'did not run'."""
    by_id = {s.call_id: s for s in exported_spans}
    history: dict[str, str] = {}
    for call_id in assistant_tool_call_ids:
        span = by_id.get(call_id)
        if span is None:
            raise TraceReconstructionError(
                f"tool call {call_id!r} referenced by assistant span but no "
                f"child span exported (dropped or aged out); state is UNKNOWN, "
                f"query idempotency ledger before re-issuing"
            )
        verify_span_complete(span)
        history[call_id] = span.arguments
    return history
