# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-write-time-trust-boundary-when-its-own-memory-poisoning-defense-becomes-the-poison-vector.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-write-time-trust-boundary-when-its-own-memory-poisoning-defense-becomes-the-poison-vector.warrant.json
# Markdown SHA-256:   76a98ab026b689a9ab9c266c1c5cc381df9be556f216c18d1c6e2bceb89a06d7
# Code AST SHA-256:   0b667114ac687a353f2e05d8fd858b659c74623a8c7710456e2854eceae8b220
# Verified Classes:   ProvenanceIndependenceError, DemotionMarginCollapse, Assertion, TrustLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional
import time


class ProvenanceIndependenceError(RuntimeError):
    """Raised when a contradiction resolution cannot prove provenance independence."""
    pass


class DemotionMarginCollapse(RuntimeError):
    """Raised when serial demotions from one provenance class exceed the safety threshold."""
    pass


@dataclass
class Assertion:
    content: str
    source_uri: str
    trust_score: float
    admitted_at: float
    superseded: bool = False


@dataclass
class TrustLedger:
    demotions_by_class: dict = field(default_factory=dict)
    demotion_times: dict = field(default_factory=dict)
    window_seconds: float = 90.0
    freeze_threshold: int = 3


def registrable_suffix(uri: str) -> str:
    # exact-suffix reputation matching; never prefix-match
    host = uri.split("//", 1)[-1].split("/", 1)[0]
    parts = host.split(".")
    return ".".join(parts[-2:]) if len(parts) >= 2 else host


def provenance_independent(a: Assertion, b: Assertion) -> bool:
    return registrable_suffix(a.source_uri) != registrable_suffix(b.source_uri)


def resolve_contradiction(
    incumbent: Assertion,
    candidate: Assertion,
    ledger: TrustLedger,
    base_margin: float = 0.05,
    k: float = 0.04,
    now: Optional[float] = None,
) -> Assertion:
    now = now if now is not None else time.time()
    cls = registrable_suffix(candidate.source_uri)

    if not provenance_independent(candidate, incumbent):
        raise ProvenanceIndependenceError(
            f"candidate {candidate.source_uri} shares provenance class with "
            f"incumbent {incumbent.source_uri}; contradiction is not independent corroboration"
        )

    # prune stale demotion timestamps
    times = [t for t in ledger.demotion_times.get(cls, []) if now - t <= ledger.window_seconds]
    ledger.demotion_times[cls] = times

    if len(times) >= ledger.freeze_threshold:
        raise DemotionMarginCollapse(
            f"provenance class {cls} has {len(times)} demotions in window; "
            f"freeze ledger and escalate to auditor instead of auto-resolving"
        )

    prior = ledger.demotions_by_class.get(cls, 0)
    required_margin = base_margin + k * prior
    delta = candidate.trust_score - incumbent.trust_score

    if delta <= required_margin:
        # quarantine: do not demote the incumbent
        candidate.superseded = False
        return incumbent

    incumbent.superseded = True
    ledger.demotions_by_class[cls] = prior + 1
    ledger.demotion_times[cls].append(now)
    return candidate
