# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-promote-an-episodic-trace-into-semantic-memory-when-the-vector-store-returns-a-near-duplicate-with-a.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-promote-an-episodic-trace-into-semantic-memory-when-the-vector-store-returns-a-near-duplicate-with-a.warrant.json
# Markdown SHA-256:   86892675a7468e3b22bca8f3b96fc2fbec09f8b732ed72a67bf2c89dd0445388
# Code AST SHA-256:   525adaa280c60a007399d6607225daabfe80ddd8c04a27cd001b628c95a7c070
# Verified Classes:   PromotionRefused, Outcome, EpisodicTrace, SemanticNode, VectorHit
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class PromotionRefused(RuntimeError):
    """Raised when an episodic trace must not be promoted to semantic memory."""


class Outcome(Enum):
    NOOP = "noop"
    UPDATE = "update"
    REFUSE_CONFLICT = "refuse_conflict"
    REFUSE_IDENTITY = "refuse_identity"


@dataclass(frozen=True)
class EpisodicTrace:
    entity_key: str          # exact, resolved via structured store
    attribute: str
    value: object
    observed_at: int         # monotonic timestamp
    source: str


@dataclass(frozen=True)
class SemanticNode:
    entity_key: str
    attribute: str
    value: object
    valid_from: int
    valid_to: int | None     # None == open interval
    source: str


@dataclass(frozen=True)
class VectorHit:
    entity_key: str          # key the embedding *claims* to match
    similarity: float


def promote(
    trace: EpisodicTrace,
    vector_hit: VectorHit,
    graph_value: object,
    existing: SemanticNode | None,
    similarity_threshold: float = 0.91,
) -> tuple[Outcome, SemanticNode | None]:
    # 1. Similarity is only a candidate generator.
    if vector_hit.similarity < similarity_threshold:
        raise PromotionRefused(
            f"similarity {vector_hit.similarity:.3f} below threshold; "
            f"trace {trace.entity_key}.{trace.attribute} stays episodic"
        )

    # 2. Identity must be exact, never inferred from proximity.
    if vector_hit.entity_key != trace.entity_key:
        raise PromotionRefused(
            f"identity mismatch: vector hit {vector_hit.entity_key!r} "
            f"!= trace {trace.entity_key!r}; near-duplicate embedding rejected"
        )

    # 3. Graph tier must not contradict the episode without explanation.
    if graph_value != trace.value and graph_value is not None:
        # value differs; only a clean temporal update is allowed
        if existing is None or existing.valid_to is not None:
            raise PromotionRefused(
                f"ambiguous update for {trace.entity_key}.{trace.attribute}: "
                f"graph={graph_value!r} episode={trace.value!r}; "
                f"no open interval to close -> conflict ledger"
            )

    # 4. No existing node: open a fresh interval.
    if existing is None:
        return Outcome.UPDATE, SemanticNode(
            entity_key=trace.entity_key,
            attribute=trace.attribute,
            value=trace.value,
            valid_from=trace.observed_at,
            valid_to=None,
            source=trace.source,
        )

    # 5. Same value: idempotent no-op.
    if existing.value == trace.value:
        return Outcome.NOOP, existing

    # 6. Genuine update: close prior interval, open new one.
    closed = SemanticNode(
        entity_key=existing.entity_key,
        attribute=existing.attribute,
        value=existing.value,
        valid_from=existing.valid_from,
        valid_to=trace.observed_at,
        source=existing.source,
    )
    opened = SemanticNode(
        entity_key=trace.entity_key,
        attribute=trace.attribute,
        value=trace.value,
        valid_from=trace.observed_at,
        valid_to=None,
        source=trace.source,
    )
    # caller persists both: closed interval + open interval
    return Outcome.UPDATE, opened
