# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-emit-a-gen-ai-prompt-lineage-span-when-attribute-schema-version-and-prompt-capture-policy-disagree-at.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-emit-a-gen-ai-prompt-lineage-span-when-attribute-schema-version-and-prompt-capture-policy-disagree-at.warrant.json
# Markdown SHA-256:   e05c5a59df4b0aef666f3faf64e06fa9bc4398a648610206886b092c2137f55e
# Code AST SHA-256:   6270056a8aa134786fb2b5d6d87f1406dd2e4c14afaf2fbdfa89ef1116e08519
# Verified Classes:   LineageEmissionRefused, SchemaVersion, CapturePolicy
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Mapping


class LineageEmissionRefused(RuntimeError):
    """Raised when (schema_version, capture_policy) is not jointly satisfiable."""
    pass


@dataclass(frozen=True)
class SchemaVersion:
    name: str
    lineage_keys: frozenset[str]  # K(S): keys that carry prompt/response lineage
    marker_key: str = "gen_ai.lineage.status"
    redacted_keys_key: str = "gen_ai.lineage.redacted_keys"


@dataclass(frozen=True)
class CapturePolicy:
    # Explicit per-key disposition. NO prefix matching, NO defaults.
    dispositions: Mapping[str, str]  # key -> "capture" | "redact" | "drop"

    def disposition_for(self, key: str) -> str | None:
        return self.dispositions.get(key)


def build_lineage_attributes(
    schema: SchemaVersion,
    policy: CapturePolicy,
    raw_prompt_attrs: Mapping[str, object],
) -> dict[str, object]:
    """
    Construct the attribute map for a GenAI lineage span, or refuse.

    Refuses (raises) when any lineage key required by the schema has no
    explicit disposition in the capture policy. Emitting a schema-valid span
    with silently-missing lineage is the failure mode this guard exists to
    prevent: downstream reconstructors fabricate lineage from a fallback
    store that has diverged from what the model actually saw.
    """
    out: dict[str, object] = {}
    redacted: list[str] = []

    for key in schema.lineage_keys:
        disp = policy.disposition_for(key)
        if disp is None:
            # No explicit disposition: the policy layer does not know this key.
            # This is the exact condition that produced fabricated lineage in
            # production after the gen_ai.prompt.* -> gen_ai.input.messages
            # migration: the prefix allowlist missed the new key and the
            # default was silent drop. Refuse instead.
            raise LineageEmissionRefused(
                f"schema {schema.name!r} requires lineage key {key!r} but "
                f"capture policy has no explicit disposition for it; "
                f"refusing to emit a span that would silently lose lineage"
            )

        if disp == "capture":
            if key in raw_prompt_attrs:
                out[key] = raw_prompt_attrs[key]
            # key absent from raw attrs is a producer bug, not a policy issue;
            # let it be absent (the marker below still records status).
        elif disp == "redact":
            out[key] = "<redacted>"
            redacted.append(key)
        elif disp == "drop":
            redacted.append(key)
        else:
            raise LineageEmissionRefused(
                f"unknown disposition {disp!r} for key {key!r}"
            )

    # Marker is mandatory and must be policy-permitted; it is in K(S).
    marker_disp = policy.disposition_for(schema.marker_key)
    if marker_disp != "capture":
        raise LineageEmissionRefused(
            f"marker key {schema.marker_key!r} must be capture-permitted; "
            f"got {marker_disp!r}. Without it, downstream reconstructors "
            f"cannot distinguish redacted lineage from absent lineage."
        )

    out[schema.marker_key] = "redacted" if redacted else "captured"
    if redacted:
        out[schema.redacted_keys_key] = ",".join(sorted(redacted))
    return out
