# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-stop-attributing-cost-when-its-own-token-stream-is-the-only-clock-span-relative-attribution-drift-under-streamed-generation.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-stop-attributing-cost-when-its-own-token-stream-is-the-only-clock-span-relative-attribution-drift-under-streamed-generation.warrant.json
# Markdown SHA-256:   7262a0b002850af0c633f9437e447b7af65d9311c0cbf0ed4cbd0c239f1d3187
# Code AST SHA-256:   3d6a1733360e236428f6d68a423aeb1bee6a46fa596c8300356d0bacf17dc8d0
# Verified Classes:   AttributionDriftError, SegmentState, Segment, AttributionLedger
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum


class AttributionDriftError(RuntimeError):
    """Raised when a token is priced against a span whose segment was not open
    at the token's arrival time, or when a nested generator's tokens are
    attributed to a paused parent stream."""


class SegmentState(Enum):
    OPEN = "open"
    PAUSED = "paused"
    CLOSED = "closed"


@dataclass
class Segment:
    span_id: str
    state: SegmentState = SegmentState.OPEN
    token_count: int = 0
    generation_active_ns: int = 0
    pending_nested: bool = False


@dataclass
class AttributionLedger:
    segments: dict[str, Segment] = field(default_factory=dict)
    granularity: str = "token"

    def open_segment(self, span_id: str) -> Segment:
        seg = Segment(span_id=span_id)
        self.segments[span_id] = seg
        return seg

    def pause(self, span_id: str, nested_generator: bool = False) -> None:
        seg = self.segments[span_id]
        seg.state = SegmentState.PAUSED
        seg.pending_nested = nested_generator

    def resume(self, span_id: str) -> None:
        seg = self.segments[span_id]
        seg.state = SegmentState.OPEN
        seg.pending_nested = False

    def attribute_token(self, span_id: str, inter_token_ns: int) -> None:
        seg = self.segments.get(span_id)
        if seg is None:
            raise AttributionDriftError(f"no segment for span {span_id}")
        if seg.state is not SegmentState.OPEN:
            # The exact invariant: a token may only be priced against a
            # segment that was open at the token's arrival time.
            raise AttributionDriftError(
                f"token arrived for span {span_id} in state {seg.state.value}; "
                f"refusing to attribute across a pause boundary"
            )
        seg.token_count += 1
        seg.generation_active_ns += inter_token_ns

    def close_turn(self, span_id: str, provider_turn_tokens: int,
                   provider_segment_tokens: int | None) -> dict:
        seg = self.segments[span_id]
        seg.state = SegmentState.CLOSED
        if provider_segment_tokens is None:
            # Condition 3 failed: cannot split the turn honestly.
            self.granularity = "turn"
            return {
                "span_id": span_id,
                "granularity": "turn",
                "tokens": provider_turn_tokens,
                "note": "provider did not report per-segment usage; "
                        "per-token attribution suppressed",
            }
        if provider_segment_tokens != seg.token_count:
            raise AttributionDriftError(
                f"segment token mismatch for {span_id}: "
                f"streamed {seg.token_count}, provider {provider_segment_tokens}"
            )
        return {
            "span_id": span_id,
            "granularity": "token",
            "tokens": seg.token_count,
            "generation_active_ns": seg.generation_active_ns,
            "per_token_ns": seg.generation_active_ns / max(seg.token_count, 1),
        }


def price_turn(ledger: AttributionLedger, span_id: str, *,
               provider_turn_tokens: int,
               provider_segment_tokens: int | None) -> dict:
    seg = ledger.segments.get(span_id)
    if seg is None:
        raise AttributionDriftError(f"unknown span {span_id}")
    if seg.pending_nested:
        raise AttributionDriftError(
            f"span {span_id} has a pending nested generator; "
            f"parent cost cannot be closed until child reports usage"
        )
    return ledger.close_turn(span_id, provider_turn_tokens, provider_segment_tokens)
