# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-demote-a-semantic-memory-to-episodic-on-retrieval-time-contradiction-the-distillation-provenance-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-demote-a-semantic-memory-to-episodic-on-retrieval-time-contradiction-the-distillation-provenance-invariant.warrant.json
# Markdown SHA-256:   988c07de585fa4a629300047d6aa3ada507d5c37807dcbd530e620d43d77e8ae
# Code AST SHA-256:   d2b41f8bc22bd5bb0adcd746860b16ba48d7de3730a996566ce8a0d46a1f2fa5
# Verified Classes:   MemoryConflictError, SemanticClaim, EpisodicTrace
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional
from datetime import datetime


class MemoryConflictError(RuntimeError):
    """Raised when a semantic claim cannot be safely adjudicated at retrieval time."""


@dataclass
class SemanticClaim:
    claim_id: str
    predicate: str
    value: str
    independent_sources: int          # post source-collapse, NOT episode count
    scope: dict                       # e.g. {"region": "EU", "currency": "EUR"}
    distilled_from: datetime
    distilled_to: datetime
    confidence: float


@dataclass
class EpisodicTrace:
    trace_id: str
    predicate: str
    value: str
    source_key: str                   # independent-source identity, not content hash
    observed_at: datetime
    scope: dict = field(default_factory=dict)


def resolve(
    claim: SemanticClaim,
    traces: list[EpisodicTrace],
) -> tuple[str, Optional[str]]:
    """
    Returns (decision, hypothesis) where decision is one of
    'use', 'contested', 'demote', 'branch'.
    Raises MemoryConflictError when provenance is insufficient to decide.
    """
    if claim.independent_sources <= 0:
        raise MemoryConflictError(
            f"claim {claim.claim_id} has no recorded independent sources; "
            "cannot weigh contradiction"
        )

    contradicting_sources: set[str] = set()
    branched = False

    for t in traces:
        if t.predicate != claim.predicate:
            continue
        if not (claim.distilled_from <= t.observed_at <= claim.distilled_to):
            continue  # already-amortized observation, not a contradiction
        if t.value == claim.value:
            continue
        # scoped-predicate mismatch -> branch, not contradiction
        if any(claim.scope.get(k) != v for k, v in t.scope.items()):
            branched = True
            continue
        contradicting_sources.add(t.source_key)

    c = len(contradicting_sources)
    s = claim.independent_sources

    if c == 0:
        return ("use", None)
    if c >= s:
        return ("demote", claim.value)          # minority hypothesis now
    # 0 < c < s: majority is NOT sufficient to act
    return ("contested", claim.value)


def require_authoritative(claim: SemanticClaim, traces: list[EpisodicTrace]) -> str:
    decision, _ = resolve(claim, traces)
    if decision != "use":
        raise MemoryConflictError(
            f"claim {claim.claim_id} is not authoritative (decision={decision}); "
            "irreversible actions blocked pending re-distillation or adjudication"
        )
    return claim.value
