# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-otel-genai-span-redaction-has-silently-desynchronized-from-the-semantic-attribute-schema-it-is-scrubbing-against.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-otel-genai-span-redaction-has-silently-desynchronized-from-the-semantic-attribute-schema-it-is-scrubbing-against.warrant.json
# Markdown SHA-256:   b050cf49a4cb417fcb8d3e5caa428c1b57bf79a008050e51134440b33fc4b25e
# Code AST SHA-256:   bf051060f62e41bfffb98c039d1b688e453d3e4f7ea2bae9e065450d03220e03
# Verified Classes:   RedactionDesyncError, Span
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass, field
from typing import Any


class RedactionDesyncError(RuntimeError):
    """Raised when an exported span contains an attribute path the ruleset never classified."""
    pass


# Paths the ruleset explicitly classifies. Subtree-aware: 'gen_ai.input.messages[*]'
# covers every element's nested paths, so encoding changes that preserve structure
# do not desync.
CLASSIFIED_SCRUB = {
    "gen_ai.prompt",
    "gen_ai.completion",
    "gen_ai.input.messages[*]",
    "gen_ai.output.messages[*]",
    "gen_ai.tool.call.arguments[*]",
}
CLASSIFIED_SAFE = {
    "gen_ai.system",
    "gen_ai.request.model",
    "gen_ai.usage.input_tokens",
    "gen_ai.usage.output_tokens",
    "gen_ai.operation.name",
}
# Paths that must never export unclassified, regardless of ruleset state.
SENSITIVE_DENYLIST = re.compile(
    r"(content|arguments|authorization|prompt|completion|messages)", re.IGNORECASE
)


@dataclass
class Span:
    name: str
    attributes: dict[str, Any] = field(default_factory=dict)


def _flatten_paths(obj: Any, prefix: str = "") -> list[str]:
    """Enumerate every leaf path, collapsing list indices to [*] so structural
    changes are visible but index churn is not."""
    paths: list[str] = []
    if isinstance(obj, dict):
        for k, v in obj.items():
            paths.extend(_flatten_paths(v, f"{prefix}.{k}" if prefix else k))
    elif isinstance(obj, list):
        for v in obj:
            paths.extend(_flatten_paths(v, f"{prefix}[*]"))
    else:
        paths.append(prefix)
    return paths


def _matches_classified(path: str, classified: set[str]) -> bool:
    # A classified subtree 'a.b[*]' covers 'a.b[*].c.d'.
    for c in classified:
        if path == c or path.startswith(c + ".") or path.startswith(c + "[*]"):
            return True
    return False


def enforce_subset_invariant(span: Span) -> Span:
    """Post-transform assertion: every emitted path must be classified.
    Called AFTER all scrubbing, on the final span. Fails closed."""
    emitted = _flatten_paths(span.attributes)
    unclassified = [
        p for p in emitted
        if not _matches_classified(p, CLASSIFIED_SCRUB)
        and not _matches_classified(p, CLASSIFIED_SAFE)
    ]
    if not unclassified:
        return span

    sensitive = [p for p in unclassified if SENSITIVE_DENYLIST.search(p)]
    if sensitive:
        # Fail closed with attribution: name the offending path, quarantine.
        raise RedactionDesyncError(
            f"span '{span.name}' emitted unclassified sensitive path(s) "
            f"{sensitive!r}; ruleset desynchronized from schema. Quarantining."
        )
    # Non-sensitive unclassified: annotate, do not silently pass.
    span.attributes["redaction.unclassified_path"] = unclassified
    return span


def redact_and_export(span: Span, exporter) -> None:
    # ... scrub CLASSIFIED_SCRUB paths in place here ...
    span = enforce_subset_invariant(span)
    exporter(span)
