# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-resolve-a-semantic-memory-contradiction-when-the-episodic-evidence-that-justified-the-older-belief-has-already-been-evicted-fro.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-resolve-a-semantic-memory-contradiction-when-the-episodic-evidence-that-justified-the-older-belief-has-already-been-evicted-fro.warrant.json
# Markdown SHA-256:   e9c407cc9bfb843a544eee432a3d0dfd46e2b439d657609d42cd199a4c340247
# Code AST SHA-256:   a18daefb2f8f2ef99e1748905d13ef410b7af0c1b9364bd2f2f93dc3570bc744
# Verified Classes:   ProvenanceOrphanedError, SemanticClaim, FreshObservation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class ProvenanceOrphanedError(RuntimeError):
    """Raised when a contradiction resolver encounters a semantic claim whose
    justifying episodic trace has been evicted by retention policy, and the
    resolver is about to treat that absence as zero support."""
    pass


@dataclass
class SemanticClaim:
    key: str
    value: str
    confidence: float
    support_count_at_distillation: int   # frozen at distillation, never decremented
    provenance_ids: list[str]
    distilled_at: datetime
    orphaned_support_carried: int = 0    # carried forward across revisions


@dataclass
class FreshObservation:
    key: str
    value: str
    confidence: float
    provenance_id: str


DELTA = 0.15
RETENTION_WEIGHT = 0.6  # decay applied to orphaned support


def _resolvable_support(claim: SemanticClaim, episodic_store: dict) -> int:
    return sum(1 for pid in claim.provenance_ids if episodic_store.get(pid) is not None)


def _effective_support(claim: SemanticClaim, episodic_store: dict) -> float:
    resolvable = _resolvable_support(claim, episodic_store)
    orphaned = claim.support_count_at_distillation - resolvable + claim.orphaned_support_carried
    return resolvable + orphaned * RETENTION_WEIGHT


def resolve_contradiction(
    old: SemanticClaim,
    new: FreshObservation,
    episodic_store: dict,
    now: datetime,
) -> dict:
    resolvable = _resolvable_support(old, episodic_store)
    orphaned = (old.support_count_at_distillation - resolvable) + old.orphaned_support_carried

    if orphaned > 0 and resolvable == 0:
        # Retention-orphaned: do NOT treat as zero support.
        if old.confidence > new.confidence + DELTA:
            return {
                "action": "stage",
                "reason": "retention_orphaned_high_confidence",
                "staged_value": new.value,
                "orphaned_support": orphaned,
            }
        # Promote, but carry the orphaned support forward.
        return {
            "action": "promote",
            "reason": "retention_orphaned_low_confidence",
            "new_claim": SemanticClaim(
                key=new.key,
                value=new.value,
                confidence=new.confidence,
                support_count_at_distillation=1,
                provenance_ids=[new.provenance_id],
                distilled_at=now,
                orphaned_support_carried=orphaned,
            ),
        }

    if orphaned > 0 and resolvable > 0:
        raise ProvenanceOrphanedError(
            f"claim {old.key!r} has {resolvable} resolvable and {orphaned} orphaned "
            f"support; resolver must not apply symmetric comparison"
        )

    # Normal symmetric resolution.
    if new.confidence > old.confidence:
        return {"action": "promote", "reason": "symmetric_newer_higher_confidence"}
    return {"action": "keep", "reason": "symmetric_old_higher_confidence"}


def apply_resolution(claim: SemanticClaim, decision: dict) -> SemanticClaim:
    action = decision["action"]
    if action == "promote" and "new_claim" in decision:
        return decision["new_claim"]
    if action == "promote" and "new_claim" not in decision:
        raise ProvenanceOrphanedError(
            "promote decision missing new_claim payload; refusing to mutate store"
        )
    return claim
