# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-genai-span-attribute-collapse-when-tool-call-token-usage-and-agent-invocation-telemetry-share-one-span.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-genai-span-attribute-collapse-when-tool-call-token-usage-and-agent-invocation-telemetry-share-one-span.warrant.json
# Markdown SHA-256:   b475c9b5c160cdfe682c2012755d7e3827f86ee5b465b519d81fa86f14605635
# Code AST SHA-256:   b8342a49ac39e228d6bde47b4f3252cb46df40cb829dad4a59626cd118f09bfc
# Verified Classes:   SpanPhase, AttributePhaseViolation, GenAISpan
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from enum import Enum, auto


class SpanPhase(Enum):
    START = auto()
    TOOL_CHILD = auto()
    USAGE_CLOSE = auto()
    END = auto()


class AttributePhaseViolation(RuntimeError):
    """Raised when a GenAI attribute is written outside its permitted lifecycle phase."""


# Which phase each attribute family may be written in.
PERMITTED_PHASE = {
    "gen_ai.agent.id": SpanPhase.START,
    "gen_ai.agent.name": SpanPhase.START,
    "gen_ai.operation.name": SpanPhase.START,
    "gen_ai.tool.name": SpanPhase.TOOL_CHILD,
    "gen_ai.tool.call.id": SpanPhase.TOOL_CHILD,
    "gen_ai.usage.input_tokens": SpanPhase.USAGE_CLOSE,
    "gen_ai.usage.output_tokens": SpanPhase.USAGE_CLOSE,
}


class GenAISpan:
    def __init__(self, span_id: str):
        self.span_id = span_id
        self.phase = SpanPhase.START
        self.attrs: dict[str, object] = {}
        self._usage_written = False

    def advance(self, new_phase: SpanPhase) -> None:
        order = [SpanPhase.START, SpanPhase.TOOL_CHILD, SpanPhase.USAGE_CLOSE, SpanPhase.END]
        if order.index(new_phase) <= order.index(self.phase):
            raise AttributePhaseViolation(
                f"span {self.span_id}: non-monotonic phase transition "
                f"{self.phase.name} -> {new_phase.name}"
            )
        self.phase = new_phase

    def set_attribute(self, key: str, value: object) -> None:
        required = PERMITTED_PHASE.get(key)
        if required is None:
            self.attrs[key] = value
            return
        if required != self.phase:
            raise AttributePhaseViolation(
                f"span {self.span_id}: attribute {key} requires phase "
                f"{required.name} but span is in {self.phase.name}"
            )
        if key.startswith("gen_ai.usage.") and self._usage_written and key in self.attrs:
            raise AttributePhaseViolation(
                f"span {self.span_id}: token-usage attribute {key} written twice "
                f"(last-writer-wins would corrupt aggregation)"
            )
        self.attrs[key] = value
        if key.startswith("gen_ai.usage."):
            self._usage_written = True


def emit_agent_turn(span: GenAISpan, tool_calls: list[str], usage: dict[str, int]) -> GenAISpan:
    span.set_attribute("gen_ai.operation.name", "chat")
    span.set_attribute("gen_ai.agent.id", "agent-7")
    if tool_calls:
        span.advance(SpanPhase.TOOL_CHILD)
        for i, tool in enumerate(tool_calls):
            child = GenAISpan(f"{span.span_id}-tool-{i}")
            child.set_attribute("gen_ai.tool.name", tool)
            child.set_attribute("gen_ai.tool.call.id", f"call-{i}")
    span.advance(SpanPhase.USAGE_CLOSE)
    span.set_attribute("gen_ai.usage.input_tokens", usage["input"])
    span.set_attribute("gen_ai.usage.output_tokens", usage["output"])
    span.advance(SpanPhase.END)
    return span


def replay_retry(span: GenAISpan) -> None:
    # A retry that reuses the span would reset START-phase attributes after USAGE_CLOSE.
    if span.phase != SpanPhase.END:
        raise AttributePhaseViolation(
            f"span {span.span_id}: retry attempted before END; open a new span instead"
        )
    span.set_attribute("gen_ai.operation.name", "execute_tool")
