# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-genai-span-attributes-as-unredactable-at-the-collector-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-genai-span-attributes-as-unredactable-at-the-collector-boundary.warrant.json
# Markdown SHA-256:   2ddf2971a7e356fd02e590f9e796a282bf8f5bac4195efb27620e7347ca7b165
# Code AST SHA-256:   f2cec75d89c7bdbc14b88cb686da3caacf2b404179da5bbaf422e29a77855d5e
# Verified Classes:   UnredactableSpanError, RedactionRuleset, RedactionResult
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Iterable

REDACTED = "[REDACTED]"
CORRELATED_USAGE_KEYS = frozenset({
    "gen_ai.usage.prompt_tokens",
    "gen_ai.usage.completion_tokens",
})


class UnredactableSpanError(RuntimeError):
    """Raised when a GenAI span cannot be proven structurally redactable.

    The span must be routed to quarantine, not exported in redacted form.
    """


@dataclass(frozen=True)
class RedactionRuleset:
    spec_version: str
    known_operation_names: frozenset[str]
    enumerated_keys: frozenset[str]
    max_prompt_index: int = 32
    surrogate_width: int = len(REDACTED)


@dataclass
class RedactionResult:
    attributes: dict[str, str]
    events: list[str] = field(default_factory=list)


def _is_content_key(key: str) -> bool:
    return (
        key.startswith("gen_ai.prompt.")
        or key.startswith("gen_ai.completion.")
        or key.startswith("gen_ai.tool.")
    ) and key.endswith((".content", ".arguments"))


def redact_genai_span(
    attributes: dict[str, str],
    ruleset: RedactionRuleset,
) -> RedactionResult:
    op = attributes.get("gen_ai.operation.name")
    if op is None or op not in ruleset.known_operation_names:
        raise UnredactableSpanError(
            f"unknown gen_ai.operation.name={op!r}; ruleset "
            f"{ruleset.spec_version} cannot prove structural invariance"
        )

    unknown = [k for k in attributes if k not in ruleset.enumerated_keys]
    if unknown:
        raise UnredactableSpanError(
            f"attributes outside ruleset enumeration: {sorted(unknown)}"
        )

    out: dict[str, str] = {}
    events: list[str] = []

    for key, value in attributes.items():
        if _is_content_key(key):
            out[key] = REDACTED[: ruleset.surrogate_width]
            events.append(f"redacted:{key}")
            continue

        if key in CORRELATED_USAGE_KEYS:
            # Coarsen to a power-of-two bucket so token counts cannot
            # reconstruct prompt length to within a few tokens.
            try:
                n = int(value)
            except ValueError as exc:
                raise UnredactableSpanError(
                    f"non-integer usage attribute {key}={value!r}"
                ) from exc
            bucket = 1 << max(n, 1).bit_length()
            out[key] = str(bucket)
            events.append(f"bucketed:{key}:{n}->{bucket}")
            continue

        out[key] = value

    # Index-bound check: any indexed content key beyond the bound must have
    # produced an explicit elision event, never a silent drop.
    for key in attributes:
        if key.startswith("gen_ai.prompt.") and _is_content_key(key):
            try:
                idx = int(key.split(".")[2])
            except (IndexError, ValueError):
                continue
            if idx >= ruleset.max_prompt_index:
                raise UnredactableSpanError(
                    f"prompt index {idx} exceeds bound "
                    f"{ruleset.max_prompt_index}; elide uniformly or quarantine"
                )

    return RedactionResult(attributes=out, events=events)


def redact_batch(
    spans: Iterable[dict[str, str]],
    ruleset: RedactionRuleset,
) -> tuple[list[RedactionResult], list[dict[str, str]]]:
    clean: list[RedactionResult] = []
    quarantine: list[dict[str, str]] = []
    for span in spans:
        try:
            clean.append(redact_genai_span(span, ruleset))
        except UnredactableSpanError:
            quarantine.append(span)
    return clean, quarantine
