# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-emit-a-parent-span-link-from-a-compaction-event-to-a-memory-write-span-whose-semantic-convention-version.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-emit-a-parent-span-link-from-a-compaction-event-to-a-memory-write-span-whose-semantic-convention-version.warrant.json
# Markdown SHA-256:   2f4af53d9d1057d63728da5b2aebd6f7bdf960264807c65a84ec7e5acf79802d
# Code AST SHA-256:   3d334182640e34e9ed1e7a1bf8f8f30958404aeffcf0e95e4f01785b34ed4eac
# Verified Classes:   SchemaGapLinkError, SourceSpan
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class SchemaGapLinkError(RuntimeError):
    """Raised when a compaction span attempts to assert provenance over a
    source memory span whose attributes cannot support the claim."""

    pass


REQUIRED_FIELDS_BY_KIND = {
    "episodic_to_semantic": ("gen_ai.memory.entry.kind", "gen_ai.memory.entry.ttl_seconds"),
    "semantic_dedup": ("gen_ai.memory.entry.kind",),
}


@dataclass
class SourceSpan:
    span_id: str
    attributes: dict


def classify_link(compaction_kind: str, source: SourceSpan, strict: bool = True) -> str:
    required = REQUIRED_FIELDS_BY_KIND[compaction_kind]
    missing = [f for f in required if source.attributes.get(f) is None]

    if not missing:
        return "distilled_from"

    if strict:
        # Provenance claim cannot be honored: refuse the link-with-claim.
        raise SchemaGapLinkError(
            f"source span {source.span_id} missing {missing} for "
            f"compaction kind {compaction_kind}; emit opaque_reference + "
            f"gen_ai.memory.compaction.schema_gap event instead"
        )

    return "opaque_reference"


def build_compaction_links(compaction_kind: str, sources: list[SourceSpan]) -> dict:
    distilled, opaque, gaps = [], [], []
    for s in sources:
        try:
            role = classify_link(compaction_kind, s, strict=True)
            distilled.append((s.span_id, role))
        except SchemaGapLinkError as exc:
            opaque.append((s.span_id, "opaque_reference"))
            gaps.append({"span_id": s.span_id, "reason": str(exc)})

    # Honest denominator: callers must report both counts, not just source_count.
    return {
        "gen_ai.memory.compaction.distilled_count": len(distilled),
        "gen_ai.memory.compaction.opaque_count": len(opaque),
        "links": distilled + opaque,
        "gap_events": gaps,
    }
