# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-attribute-a-genai-span-to-the-model-that-actually-answered-when-the-tool-call-and-the-completion-share-one-trace-context.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-attribute-a-genai-span-to-the-model-that-actually-answered-when-the-tool-call-and-the-completion-share-one-trace-context.warrant.json
# Markdown SHA-256:   46fc1f179af0aaad144a7893a73f71285b70c40a552011d3ddf1cbac941de880
# Code AST SHA-256:   2678fc8290d8c889a10dc63fcf6b1898ebeb11c9734807d2e62bbc3d517d46d6
# Verified Classes:   GenAIAttributionError, GenAISpan
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class GenAIAttributionError(RuntimeError):
    """Raised when a span cannot be validly attributed to a single model round-trip."""


@dataclass
class GenAISpan:
    name: str
    request_models: list[str] = field(default_factory=list)
    response_models: list[str] = field(default_factory=list)
    input_tokens: int = 0
    output_tokens: int = 0
    overlapping_tool_ms: float = 0.0
    attribution_status: Optional[str] = None

    def record_request(self, model: str, input_tokens: int) -> None:
        self.request_models.append(model)
        self.input_tokens += input_tokens

    def record_response(self, model: str, output_tokens: int) -> None:
        self.response_models.append(model)
        self.output_tokens += output_tokens

    def record_tool_overlap(self, ms: float) -> None:
        self.overlapping_tool_ms += ms


def finalize_genai_span(span: GenAISpan, strict: bool = True) -> GenAISpan:
    """
    Enforce the attribution invariant at span close:
      - exactly one request model and one response model
      - zero overlapping tool execution
      - tokens written once (single round-trip)
    If violated, either raise (strict) or degrade by stripping
    gen_ai.response.model so no false attribution is emitted.
    """
    distinct_req = set(span.request_models)
    distinct_resp = set(span.response_models)

    violations = []
    if len(distinct_req) > 1:
        violations.append(f"multiple request models: {sorted(distinct_req)}")
    if len(distinct_resp) > 1:
        violations.append(f"multiple response models: {sorted(distinct_resp)}")
    if span.overlapping_tool_ms > 0.0:
        violations.append(f"tool overlap {span.overlapping_tool_ms:.1f}ms inside GenAI span")
    if len(span.request_models) > 1 or len(span.response_models) > 1:
        violations.append("token attributes accumulated across >1 round-trip")

    if not violations:
        span.attribution_status = "single_round_trip"
        return span

    if strict:
        raise GenAIAttributionError(
            "GenAI span cannot be attributed to a single model round-trip: "
            + "; ".join(violations)
            + ". Split into per-call child spans or emit with attribution_status='aggregated'."
        )

    # Degraded emission: keep tokens (they are real), drop model attribution.
    span.response_models = []
    span.attribution_status = "aggregated"
    return span


def emit_agent_step(spans: list[GenAISpan], strict: bool = True) -> list[GenAISpan]:
    out = []
    for s in spans:
        out.append(finalize_genai_span(s, strict=strict))
    return out
