# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-contradictory-episodic-memory-before-semantic-consolidation-and-how-does-retrieval-time-resolution-fail.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-contradictory-episodic-memory-before-semantic-consolidation-and-how-does-retrieval-time-resolution-fail.warrant.json
# Markdown SHA-256:   ea5d3637d89fef520cc43ed60b2435a72d2e5b5039b19431507662f43763a1ff
# Code AST SHA-256:   afe64d776a1a9b8bbd60ef067acc70bc5dacc4c11fc6de3cf6c634086272a30d
# Verified Classes:   MemoryIntegrityError, FactState, SemanticFact, SemanticStore
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class MemoryIntegrityError(RuntimeError):
    """Raised when the semantic store is in a state that permits silent
    contradiction resolution by retrieval truncation."""


class FactState(Enum):
    LIVE = "live"
    QUARANTINED = "quarantined"


@dataclass
class SemanticFact:
    entity: str
    attribute: str
    value: object
    source_weight: float
    episode_id: int
    state: FactState = FactState.LIVE
    conflict_with: Optional[int] = None  # episode_id of the competing fact

    @property
    def key(self) -> tuple[str, str]:
        return (self.entity, self.attribute)


@dataclass
class SemanticStore:
    facts: list[SemanticFact] = field(default_factory=list)

    def write(self, new_fact: SemanticFact) -> None:
        """Enforce the invariant: no two LIVE, unflagged facts for one key."""
        existing = [f for f in self.facts if f.key == new_fact.key and f.state == FactState.LIVE]
        if existing:
            # A conflict exists. Quarantine the new fact and cross-link.
            new_fact.state = FactState.QUARANTINED
            new_fact.conflict_with = existing[0].episode_id
            existing[0].conflict_with = new_fact.episode_id
        self.facts.append(new_fact)

    def retrieve_for_action(self, entity: str, attribute: str) -> SemanticFact:
        """Retrieval that must not hide contradictions. Halts on unresolved conflict."""
        key = (entity, attribute)
        candidates = [f for f in self.facts if f.key == key]
        if not candidates:
            raise MemoryIntegrityError(
                f"No fact for {key}; refusing to act on absent memory."
            )
        live = [f for f in candidates if f.state == FactState.LIVE]
        quarantined = [f for f in candidates if f.state == FactState.QUARANTINED]
        if quarantined:
            # The forbidden zone: a live fact coexists with an unresolved competitor.
            raise MemoryIntegrityError(
                f"Unresolved contradiction on {key}: live ep={live[0].episode_id} "
                f"value={live[0].value!r} vs quarantined ep={quarantined[0].episode_id} "
                f"value={quarantined[0].value!r}. Resolve with provenance before acting."
            )
        if len(live) > 1:
            # Should be unreachable if write() is the only mutation path.
            raise MemoryIntegrityError(
                f"Invariant violated: {len(live)} live facts for {key}. Store corrupted."
            )
        return live[0]


def plan_delivery(store: SemanticStore, vendor: str, quantity: int) -> dict:
    fact = store.retrieve_for_action(vendor, "lead_time_days")
    if not isinstance(fact.value, int) or fact.value <= 0:
        raise MemoryIntegrityError(
            f"Lead time for {vendor} is not a usable integer: {fact.value!r} "
            f"(ep={fact.episode_id}). Cannot schedule."
        )
    return {"vendor": vendor, "quantity": quantity, "lead_time_days": fact.value}
