#!/usr/bin/env python3
"""
ONE BIG BACKEND — LAYER 0: BELNAP B4 EPISTEMIC COMMIT FIREWALL (`obb_epistemic_lattice.py`)
License: GNU AGPLv3
External Dependencies: 0 (100% Python Standard Library + local `obb_primitives`)

Implements Belnap's four-valued epistemic lattice B4 = P({T, F}) (Belnap 1977; Fitting 1991)
for deterministic AI-agent commit gating:
  - UNKNOWN       (emptyset / 0)  : unconfirmed draft or LLM-synthesized claim
  - VERIFIED      ({T} / +1)      : human-attested or deterministic measurement
  - FALSIFIED     ({F} / -1)      : failed invariant or physical/accounting check
  - CONTRADICTORY ({T, F} / TOP)  : conflicting observations quarantined for human review

Key invariants:
  1. Node 0 Zero-PII Floor (`ObbSafetyFloor`) blocks forbidden PII before state or wire egress.
  2. LLM Source Clamp: any claim with `source_kind == LLM_SYNTHESIS` attempting `VERIFIED` is
     deterministically clamped to `UNKNOWN` (`staged_unconfirmed`).
  3. Belnap Knowledge Join (`v_k` = set union on P({T, F})): conflicting observations join to
     `CONTRADICTORY` and quarantine both versions rather than silently overwriting last-write-wins.
  4. 1-Click Atomic Rollback (`ObbUndoEngine`) restores prior state while keeping full audit logs.
"""

from __future__ import annotations

from dataclasses import dataclass
from enum import Enum
from typing import Any, Callable, Dict, FrozenSet, Mapping, Optional

from obb_primitives import (
    ObbLibraryLedger,
    ObbSafetyFloor,
    ObbUndoEngine,
    PhysicsConservationFraudError,
    StateSnapshot,
    canonical_sha256,
    deep_freeze,
    deep_thaw,
)


class EpistemicBoundaryError(ValueError):
    """Raised when an unverified or falsified claim attempts to cross a VERIFIED commit boundary."""


class EpistemicContradictionError(EpistemicBoundaryError):
    """Raised when a subject enters Belnap TOP (CONTRADICTORY) and requires human resolution."""


class EpistemicTruth(Enum):
    """Belnap four-valued epistemic lattice B4 = P({T, F})."""

    UNKNOWN = "UNKNOWN"
    VERIFIED = "VERIFIED"
    FALSIFIED = "FALSIFIED"
    CONTRADICTORY = "CONTRADICTORY"

    def evidence_set(self) -> FrozenSet[str]:
        if self is EpistemicTruth.UNKNOWN:
            return frozenset()
        if self is EpistemicTruth.VERIFIED:
            return frozenset({"T"})
        if self is EpistemicTruth.FALSIFIED:
            return frozenset({"F"})
        return frozenset({"T", "F"})

    def trit_code(self) -> Optional[int]:
        if self is EpistemicTruth.UNKNOWN:
            return 0
        if self is EpistemicTruth.VERIFIED:
            return 1
        if self is EpistemicTruth.FALSIFIED:
            return -1
        return None  # Belnap TOP ({T, F})

    @classmethod
    def from_evidence_set(cls, evidence: FrozenSet[str]) -> "EpistemicTruth":
        if evidence == frozenset():
            return cls.UNKNOWN
        if evidence == frozenset({"T"}):
            return cls.VERIFIED
        if evidence == frozenset({"F"}):
            return cls.FALSIFIED
        if evidence == frozenset({"T", "F"}):
            return cls.CONTRADICTORY
        raise ValueError(f"Invalid Belnap evidence set: {evidence!r}")


def k3_not(value: EpistemicTruth) -> EpistemicTruth:
    if value is EpistemicTruth.VERIFIED:
        return EpistemicTruth.FALSIFIED
    if value is EpistemicTruth.FALSIFIED:
        return EpistemicTruth.VERIFIED
    return value


def k3_and(a: EpistemicTruth, b: EpistemicTruth) -> EpistemicTruth:
    if a is EpistemicTruth.FALSIFIED or b is EpistemicTruth.FALSIFIED:
        return EpistemicTruth.FALSIFIED
    if a is EpistemicTruth.CONTRADICTORY or b is EpistemicTruth.CONTRADICTORY:
        return EpistemicTruth.CONTRADICTORY
    if a is EpistemicTruth.UNKNOWN or b is EpistemicTruth.UNKNOWN:
        return EpistemicTruth.UNKNOWN
    return EpistemicTruth.VERIFIED


def k3_or(a: EpistemicTruth, b: EpistemicTruth) -> EpistemicTruth:
    if a is EpistemicTruth.VERIFIED or b is EpistemicTruth.VERIFIED:
        return EpistemicTruth.VERIFIED
    if a is EpistemicTruth.CONTRADICTORY or b is EpistemicTruth.CONTRADICTORY:
        return EpistemicTruth.CONTRADICTORY
    if a is EpistemicTruth.UNKNOWN or b is EpistemicTruth.UNKNOWN:
        return EpistemicTruth.UNKNOWN
    return EpistemicTruth.FALSIFIED


def knowledge_join(a: EpistemicTruth, b: EpistemicTruth) -> EpistemicTruth:
    """Belnap Knowledge Join (v_k): set union in P({T, F})."""
    return EpistemicTruth.from_evidence_set(a.evidence_set() | b.evidence_set())


def knowledge_meet(a: EpistemicTruth, b: EpistemicTruth) -> EpistemicTruth:
    """Belnap Knowledge Meet (^_k): set intersection in P({T, F})."""
    return EpistemicTruth.from_evidence_set(a.evidence_set() & b.evidence_set())


class SourceKind(Enum):
    LLM_SYNTHESIS = "LLM_SYNTHESIS"
    HUMAN_ATTESTED = "HUMAN_ATTESTED"
    DETERMINISTIC_MEASUREMENT = "DETERMINISTIC_MEASUREMENT"
    CRYPTOGRAPHIC_RECEIPT = "CRYPTOGRAPHIC_RECEIPT"
    HARDWARE_PUF = "HARDWARE_PUF"


@dataclass(frozen=True)
class EpistemicClaim:
    claim_id: str
    subject: str
    payload: Any
    payload_hash: str
    truth_value: EpistemicTruth
    source_kind: SourceKind
    source_id: str
    llm_clamped: bool
    claim_hash: str
    note: str = ""

    def is_modal_box(self) -> bool:
        return self.truth_value is EpistemicTruth.VERIFIED

    def to_wire_dict(self) -> Dict[str, Any]:
        return {
            "claim_id": self.claim_id,
            "subject": self.subject,
            "payload": deep_thaw(self.payload),
            "payload_hash": self.payload_hash,
            "truth_value": self.truth_value.value,
            "source_kind": self.source_kind.value,
            "source_id": self.source_id,
            "llm_clamped": self.llm_clamped,
            "claim_hash": self.claim_hash,
            "note": self.note,
        }


class SweetbrierEpistemicGate:
    """Belnap B4 commit firewall with LLM Source Clamp, Zero-PII floor, and 1-Click Undo."""

    def __init__(
        self,
        node_id: str,
        safety_floor: Optional[ObbSafetyFloor] = None,
        undo_engine: Optional[ObbUndoEngine] = None,
    ) -> None:
        self.node_id = node_id
        self.safety_floor = safety_floor or ObbSafetyFloor()
        self.ledger = ObbLibraryLedger(safety_floor=self.safety_floor)
        self.undo_engine = undo_engine or ObbUndoEngine(
            initial_state={
                "node_id": node_id,
                "verified_state": {},
                "staged_unconfirmed": {},
                "quarantined_conflicts": {},
            },
            ledger=self.ledger,
        )
        self._claims_by_subject: Dict[str, EpistemicClaim] = {}

    def claims_by_subject(self) -> Dict[str, EpistemicClaim]:
        return dict(self._claims_by_subject)

    def _build_claim(
        self,
        claim_id: str,
        subject: str,
        frozen_payload: Any,
        truth_value: EpistemicTruth,
        source_kind: SourceKind,
        source_id: str,
        llm_clamped: bool,
        note: str,
    ) -> EpistemicClaim:
        p_hash = canonical_sha256(frozen_payload)
        c_hash = canonical_sha256(
            {
                "node_id": self.node_id,
                "claim_id": claim_id,
                "subject": subject,
                "payload_hash": p_hash,
                "truth_value": truth_value.value,
                "source_kind": source_kind.value,
                "source_id": source_id,
                "llm_clamped": llm_clamped,
            }
        )
        return EpistemicClaim(
            claim_id=claim_id,
            subject=subject,
            payload=frozen_payload,
            payload_hash=p_hash,
            truth_value=truth_value,
            source_kind=source_kind,
            source_id=source_id,
            llm_clamped=llm_clamped,
            claim_hash=c_hash,
            note=note,
        )

    def ingest(
        self,
        claim_id: str,
        subject: str,
        payload: Mapping[str, Any],
        proposed_truth: EpistemicTruth,
        source_kind: SourceKind,
        source_id: str,
        physics_verifier: Optional[Callable[[Mapping[str, Any]], None]] = None,
        note: str = "",
    ) -> EpistemicClaim:
        # Gate 1: Node 0 Zero-PII Floor
        self.safety_floor.assert_clean(payload)
        frozen_payload = deep_freeze(payload)

        # Gate 2: LLM Source Clamp — LLM_SYNTHESIS may never self-certify VERIFIED
        effective_truth = proposed_truth
        llm_clamped = False
        if source_kind is SourceKind.LLM_SYNTHESIS and proposed_truth is EpistemicTruth.VERIFIED:
            effective_truth = EpistemicTruth.UNKNOWN
            llm_clamped = True

        # Gate 3: Deterministic accounting/physics conservation verifier
        if physics_verifier is not None:
            try:
                physics_verifier(payload)
            except PhysicsConservationFraudError as exc:
                effective_truth = EpistemicTruth.FALSIFIED
                note = f"{note} [FALSIFIED: {exc}]".strip()

        claim = self._build_claim(
            claim_id=claim_id,
            subject=subject,
            frozen_payload=frozen_payload,
            truth_value=effective_truth,
            source_kind=source_kind,
            source_id=source_id,
            llm_clamped=llm_clamped,
            note=note,
        )
        self.ledger.append(
            event_type="CLAIM_INGESTED",
            actor=source_id,
            payload=claim.to_wire_dict(),
            note=note or f"Ingested {claim_id} as {effective_truth.value}.",
        )
        return claim

    def promote_with_verification(
        self,
        claim: EpistemicClaim,
        verifier_id: str,
        verification_note: str,
        verdict: EpistemicTruth = EpistemicTruth.VERIFIED,
        new_source_kind: SourceKind = SourceKind.HUMAN_ATTESTED,
    ) -> EpistemicClaim:
        if new_source_kind is SourceKind.LLM_SYNTHESIS and verdict is EpistemicTruth.VERIFIED:
            raise EpistemicBoundaryError("LLM_SYNTHESIS cannot promote a claim to VERIFIED.")
        promoted = self._build_claim(
            claim_id=f"{claim.claim_id}:verified",
            subject=claim.subject,
            frozen_payload=claim.payload,
            truth_value=verdict,
            source_kind=new_source_kind,
            source_id=verifier_id,
            llm_clamped=False,
            note=verification_note,
        )
        self.ledger.append(
            event_type="CLAIM_PROMOTED",
            actor=verifier_id,
            payload=promoted.to_wire_dict(),
            note=verification_note,
        )
        return promoted

    def merge_into_subject(self, incoming: EpistemicClaim) -> StateSnapshot:
        """
        Gate 4: Belnap Knowledge Join merge into partitioned production state.
        If a VERIFIED subject receives a conflicting VERIFIED payload with a different
        payload_hash, both claims are quarantined in `quarantined_conflicts` (Belnap TOP).
        """
        state = self.undo_engine.current_state
        subj = incoming.subject
        existing = self._claims_by_subject.get(subj)

        if incoming.truth_value is EpistemicTruth.UNKNOWN:
            state["staged_unconfirmed"][subj] = incoming.to_wire_dict()
            self._claims_by_subject.setdefault(subj, incoming)
            return self.undo_engine.commit(f"STAGE:{subj}", state)

        if incoming.truth_value is EpistemicTruth.FALSIFIED:
            return self.undo_engine.commit(f"FALSIFIED_BLOCKED:{subj}", state)

        if (
            existing is not None
            and existing.truth_value is EpistemicTruth.VERIFIED
            and incoming.truth_value is EpistemicTruth.VERIFIED
            and existing.payload_hash != incoming.payload_hash
        ):
            conflict_payload = deep_freeze(
                {
                    "existing": existing.to_wire_dict(),
                    "incoming": incoming.to_wire_dict(),
                }
            )
            conflict_claim = self._build_claim(
                claim_id=f"CONFLICT:{existing.claim_id}:{incoming.claim_id}",
                subject=subj,
                frozen_payload=conflict_payload,
                truth_value=EpistemicTruth.CONTRADICTORY,
                source_kind=SourceKind.DETERMINISTIC_MEASUREMENT,
                source_id=self.node_id,
                llm_clamped=False,
                note="Conflicting verified observations quarantined as Belnap TOP.",
            )
            state["verified_state"].pop(subj, None)
            state["quarantined_conflicts"][subj] = conflict_claim.to_wire_dict()
            self._claims_by_subject[subj] = conflict_claim
            return self.undo_engine.commit(f"QUARANTINE_TOP:{subj}", state)

        if existing is not None:
            joined = knowledge_join(existing.truth_value, incoming.truth_value)
            if joined is EpistemicTruth.CONTRADICTORY:
                state["verified_state"].pop(subj, None)
                state["quarantined_conflicts"][subj] = {
                    "existing": existing.to_wire_dict(),
                    "incoming": incoming.to_wire_dict(),
                }
                self._claims_by_subject[subj] = incoming
                return self.undo_engine.commit(f"QUARANTINE_JOIN_TOP:{subj}", state)

        state["staged_unconfirmed"].pop(subj, None)
        state["verified_state"][subj] = incoming.to_wire_dict()
        self._claims_by_subject[subj] = incoming
        return self.undo_engine.commit(f"VERIFY:{subj}", state)

    def resolve_contradiction(
        self,
        subject: str,
        human_auditor_id: str,
        resolved_payload: Mapping[str, Any],
        resolution_verdict: EpistemicTruth = EpistemicTruth.VERIFIED,
        resolution_reason: str = "",
    ) -> StateSnapshot:
        self.safety_floor.assert_clean(resolved_payload)
        frozen = deep_freeze(resolved_payload)
        resolved = self._build_claim(
            claim_id=f"RESOLVED:{subject}",
            subject=subject,
            frozen_payload=frozen,
            truth_value=resolution_verdict,
            source_kind=SourceKind.HUMAN_ATTESTED,
            source_id=human_auditor_id,
            llm_clamped=False,
            note=resolution_reason,
        )
        state = self.undo_engine.current_state
        state["quarantined_conflicts"].pop(subject, None)
        state["staged_unconfirmed"].pop(subject, None)
        if resolution_verdict is EpistemicTruth.VERIFIED:
            state["verified_state"][subject] = resolved.to_wire_dict()
        self._claims_by_subject[subject] = resolved
        return self.undo_engine.commit(f"RESOLVE:{subject}", state)

    @staticmethod
    def assert_commit_ready(claim: EpistemicClaim) -> None:
        if claim.truth_value is EpistemicTruth.CONTRADICTORY:
            raise EpistemicContradictionError(
                f"Claim '{claim.claim_id}' is CONTRADICTORY (Belnap TOP); human reconciliation required."
            )
        if claim.truth_value is not EpistemicTruth.VERIFIED:
            raise EpistemicBoundaryError(
                f"Claim '{claim.claim_id}' has truth={claim.truth_value.value}; only VERIFIED may commit."
            )

    def commit_verified(self, label: str, claim: EpistemicClaim) -> StateSnapshot:
        self.assert_commit_ready(claim)
        state = self.undo_engine.current_state
        state["staged_unconfirmed"].pop(claim.subject, None)
        state["verified_state"][claim.subject] = claim.to_wire_dict()
        self._claims_by_subject[claim.subject] = claim
        return self.undo_engine.commit(label, state)

    def stage_unconfirmed(self, label: str, claim: EpistemicClaim) -> StateSnapshot:
        state = self.undo_engine.current_state
        state["staged_unconfirmed"][claim.subject] = claim.to_wire_dict()
        self._claims_by_subject.setdefault(claim.subject, claim)
        return self.undo_engine.commit(label, state)

    def undo_last_commit(self) -> StateSnapshot:
        snap = self.undo_engine.undo()
        state = self.undo_engine.current_state
        # Resync claims map from restored verified_state
        self._claims_by_subject.clear()
        for lane_key in ("verified_state", "staged_unconfirmed"):
            for subj, raw in state.get(lane_key, {}).items():
                self._claims_by_subject[subj] = self._build_claim(
                    claim_id=raw["claim_id"],
                    subject=raw["subject"],
                    frozen_payload=deep_freeze(raw["payload"]),
                    truth_value=EpistemicTruth(raw["truth_value"]),
                    source_kind=SourceKind(raw["source_kind"]),
                    source_id=raw["source_id"],
                    llm_clamped=bool(raw["llm_clamped"]),
                    note=raw.get("note", ""),
                )
        return snap
