# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-fail-to-detect-memory-poisoning-when-write-audit-trail-integrity-is-conflated-with-semantic-consistency.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-fail-to-detect-memory-poisoning-when-write-audit-trail-integrity-is-conflated-with-semantic-consistency.warrant.json
# Markdown SHA-256:   b47610b081aa7b0670f69d7b87136ad2880262970f6dbd7c3e0b81d581752737
# Code AST SHA-256:   e9a18efe70e14591e5fce43e46ac6ec00124eee75b03cd2ad94d8e2719b036cd
# Verified Classes:   MemoryIntegrityBlindSpot, MemoryEntry
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Sequence


class MemoryIntegrityBlindSpot(RuntimeError):
    """Raised when audit-trail and drift checks both pass but a cross-entry
    contradiction is detected, indicating the instance is in the blind spot
    where neither subsystem can see the poisoning."""
    pass


@dataclass(frozen=True)
class MemoryEntry:
    entry_id: str
    principal_id: str
    payload: str
    embedding: tuple[float, ...]
    prev_hash: str
    entry_hash: str


def verify_audit_chain(entries: Sequence[MemoryEntry]) -> bool:
    prev = "0" * 64
    for e in entries:
        expected = hashlib.sha256(
            (e.principal_id + e.payload + prev).encode()
        ).hexdigest()
        if e.entry_hash != expected or e.prev_hash != prev:
            return False
        prev = e.entry_hash
    return True


def drift_distance(centroid: tuple[float, ...],
                   reference: tuple[float, ...]) -> float:
    return sum((a - b) ** 2 for a, b in zip(centroid, reference)) ** 0.5


def detect_paraphrase_poisoning(
    entries: Sequence[MemoryEntry],
    reference_centroid: tuple[float, ...],
    drift_threshold: float = 0.18,
    per_write_threshold: float = 0.05,
) -> None:
    """Both subsystems return clean; cross-entry check is the only defense."""
    audit_ok = verify_audit_chain(entries)
    if not audit_ok:
        raise MemoryIntegrityBlindSpot(
            "audit chain broken; this is the auditable case, not the blind spot"
        )

    n = len(entries)
    centroid = tuple(
        sum(e.embedding[i] for e in entries) / n
        for i in range(len(entries[0].embedding))
    )
    drift = drift_distance(centroid, reference_centroid)
    if drift >= drift_threshold:
        raise MemoryIntegrityBlindSpot(
            f"drift {drift:.3f} exceeds threshold; monitor would have fired"
        )

    # Audit clean AND drift clean. Now the cross-entry check.
    by_principal: dict[str, list[MemoryEntry]] = {}
    for e in entries:
        by_principal.setdefault(e.principal_id, []).append(e)

    for principal, group in by_principal.items():
        for i, a in enumerate(group):
            for b in group[i + 1:]:
                if _claims_contradict(a.payload, b.payload):
                    raise MemoryIntegrityBlindSpot(
                        f"principal {principal} holds contradictory entries "
                        f"{a.entry_id} and {b.entry_id} while audit and drift "
                        f"both report clean (drift={drift:.3f})"
                    )


def _claims_contradict(a: str, b: str) -> bool:
    # Placeholder for claim-extraction + NLI contradiction model.
    # Paraphrase-poisoning preserves embedding locality, so this must
    # operate on extracted claims, not embeddings.
    return False
