# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-forgets-a-memory-it-still-needs-to-cite-consent-aware-deletion-racing-an-in-flight-audit-replay.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-forgets-a-memory-it-still-needs-to-cite-consent-aware-deletion-racing-an-in-flight-audit-replay.warrant.json
# Markdown SHA-256:   925524416787749b6a0d40d9a12e3c417ddc86050ed87e973e04af3de0232b7a
# Code AST SHA-256:   43623269774fe0c558f03f9126a611fb61ec9e425e1bcd66a0aeea35439078b2
# Verified Classes:   CitationIntegrityError, Resolution, Citation, Tombstone
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

import hashlib
from dataclasses import dataclass
from enum import Enum


class CitationIntegrityError(RuntimeError):
    """Raised when a replayed action's justification cannot be lawfully resolved."""


class Resolution(Enum):
    JUSTIFIED = "justified"
    JUSTIFIED_BY_TOMBSTONE = "justified_by_tombstone"
    UNJUSTIFIABLE = "unjustifiable"


@dataclass(frozen=True)
class Citation:
    memory_id: str
    digest: str  # sha256 of record content captured at commit time


@dataclass(frozen=True)
class Tombstone:
    memory_id: str
    digest: str
    deleted_at: str
    warrant_id: str


def _digest(content: str) -> str:
    return hashlib.sha256(content.encode("utf-8")).hexdigest()


def resolve_citation(
    citation: Citation,
    read_status: str,          # "PRESENT" | "DELETED_CONSENT" | "NEVER_EXISTED" | "EXPIRED_DECAY"
    tombstone: Tombstone | None,
) -> Resolution:
    if read_status in ("PRESENT", "EXPIRED_DECAY"):
        # Decay/invalidation never removes bytes; the record still justifies the past action.
        return Resolution.JUSTIFIED

    if read_status == "DELETED_CONSENT":
        if tombstone is None:
            # Lawful erasure with no journal tombstone: cannot distinguish from tampering.
            raise CitationIntegrityError(
                f"consent deletion of {citation.memory_id} has no journal tombstone; "
                "replay cannot proceed and must NOT re-derive from surviving memory"
            )
        if tombstone.digest != citation.digest:
            raise CitationIntegrityError(
                f"tombstone digest mismatch for {citation.memory_id}: "
                f"commit={citation.digest} tombstone={tombstone.digest}"
            )
        return Resolution.JUSTIFIED_BY_TOMBSTONE

    if read_status == "NEVER_EXISTED":
        # A citation to a record that never existed at commit time is a fabrication.
        raise CitationIntegrityError(
            f"citation to {citation.memory_id} references a record that never existed"
        )

    raise CitationIntegrityError(f"unknown read status: {read_status!r}")
