#!/usr/bin/env python3
"""
Cryptographer-Grade Automated Regression & Security Verification Suite (`test_honesty_layer_v2.py`)

Verifies every v2 security fix and mathematical invariant across all 6 stdlib modules:
  1. Layer 0 (`obb_primitives` + `obb_epistemic_lattice`):
     - Zero-PII floor blocks SSN, phone, email, and forbidden keys
     - LLM Source Clamp traps LLM_SYNTHESIS attempting VERIFIED -> UNKNOWN
     - Belnap B4 Knowledge Join quarantines conflicting verified claims as TOP
     - 1-Click atomic rollback restores state while preserving hash-chained ledger integrity
  2. Shield 1 (`obb_fine_grained_pow`):
     - Proves `evaluate_pov_monomial_attack` matches `evaluate_pov` identically at d=4
     - Verifies production issuer REJECTS insecure d < min_secure_dimension(n)
     - Verifies full solve + Lagrange verification + forgery rejection + replay rejection at secure (n=64, d=16)
     - Verifies unauthenticated `issue_challenge()` floods NEVER trigger epoch rotation or unbounded memory
  3. Shield 3 (`obb_info_theoretic_channel`):
     - Verifies Encrypt-then-MAC round-trip + ciphertext bit-flip detection + replay rejection
     - Proves 1-packet pre-MAC pad-wipe DoS (`mac_pad_len=1_000_000_000`, out-of-window offsets,
       and single forged MAC) DOES NOT wipe or desync the receiver pad
     - Proves bounded 3-strike quarantine works on repeated bad MACs against a slot
     - Proves crash-safe `FileBackedPadStore` persistence prevents two-time pad across restarts
     - Proves `ShamirQuorum` catches a corrupted extra share via Reed-Solomon consistency check
  4. Shield 2 (`obb_coupled_tile_sim`):
     - Verifies unit-cell pairwise-order entropy bound (~9.17 bits) & 16-tile array (~146.7 bits)
     - Verifies `DifferentialTilePair` cancels common-mode V_DD and FR-4 humidity epsilon_r drift
       while STILL catching localized invasive microprobe Delta-C_probe loading
  5. Layer 1 (`obb_xroad_epistemic_sidecar`):
     - Verifies authentic NIIS `/r1/...` path and `X-Road-Client` validation
     - Blocks LLM self-certified VERIFIED egress and PII leaks before NIIS Security Server signing
     - Clears human-attested zero-PII payloads with explicit `X-Sweetbrier-*` provenance headers
"""

from __future__ import annotations

import os
import tempfile
import unittest

from obb_coupled_tile_sim import (
    CMOS_28NM_SILICON,
    MAX_UNIT_CELL_ORDER_ENTROPY_BITS,
    PCB_FR4_COUPLED_STRIP,
    CoupledTile3x3,
    CoupledTileArray,
    DifferentialTilePair,
)
from obb_epistemic_lattice import (
    EpistemicTruth,
    SourceKind,
    SweetbrierEpistemicGate,
    knowledge_join,
)
from obb_fine_grained_pow import (
    FineGrainedOvIssuer,
    FineGrainedPowError,
    FineGrainedSolution,
    apply_pov_automorphism,
    evaluate_pov,
    evaluate_pov_monomial_attack,
    min_secure_dimension,
    solve_ov_challenge,
)
from obb_info_theoretic_channel import (
    AlgorithmicaCivicNode,
    FileBackedPadStore,
    InfoTheoreticEnvelope,
    InfoTheoreticSecurityError,
    OneTimePadBook,
    PadReuseError,
    QuorumCorruptionError,
    ShamirQuorum,
    WegmanCarterMac,
    WitnessShare,
)
from obb_primitives import (
    PhysicsConservationFraudError,
    SafetyFloorViolationError,
)
from obb_xroad_epistemic_sidecar import (
    XRoadEpistemicSidecar,
    XRoadRestRequest,
    XRoadSidecarPolicyError,
)


class TestLayer0EpistemicFirewall(unittest.TestCase):
    def test_pii_clamp_conflict_and_undo(self) -> None:
        gate = SweetbrierEpistemicGate("US-VA-ROA/NGO/test-node")

        # 1. Node 0 Zero-PII Floor
        with self.assertRaises(SafetyFloorViolationError):
            gate.ingest(
                claim_id="c-pii",
                subject="guests:intake",
                payload={"count": 1, "phone": "540-555-0199"},
                proposed_truth=EpistemicTruth.UNKNOWN,
                source_kind=SourceKind.LLM_SYNTHESIS,
                source_id="bot",
            )

        # 2. LLM Source Clamp
        llm_claim = gate.ingest(
            claim_id="c-llm",
            subject="meals:sunday",
            payload={"meals_confirmed": 240},
            proposed_truth=EpistemicTruth.VERIFIED,
            source_kind=SourceKind.LLM_SYNTHESIS,
            source_id="triage_bot",
        )
        self.assertEqual(llm_claim.truth_value, EpistemicTruth.UNKNOWN)
        self.assertTrue(llm_claim.llm_clamped)

        # 3. Physics/accounting conservation failure -> FALSIFIED
        def check_balance(p):
            if p["opening"] - p["disbursed"] != p["closing"]:
                raise PhysicsConservationFraudError("Balance mismatch")

        bad_bal = gate.ingest(
            claim_id="c-bal",
            subject="treasury:nov",
            payload={"opening": 500, "disbursed": 180, "closing": 340},
            proposed_truth=EpistemicTruth.VERIFIED,
            source_kind=SourceKind.DETERMINISTIC_MEASUREMENT,
            source_id="reconciler",
            physics_verifier=check_balance,
        )
        self.assertEqual(bad_bal.truth_value, EpistemicTruth.FALSIFIED)

        # 4. Belnap TOP quarantine on conflicting verified measurements + 1-Click Undo
        c1 = gate.ingest(
            claim_id="c-bay-1",
            subject="inventory:bay_4",
            payload={"pallets": 12},
            proposed_truth=EpistemicTruth.VERIFIED,
            source_kind=SourceKind.DETERMINISTIC_MEASUREMENT,
            source_id="dock_scanner",
        )
        gate.merge_into_subject(c1)
        c2 = gate.ingest(
            claim_id="c-bay-2",
            subject="inventory:bay_4",
            payload={"pallets": 9},
            proposed_truth=EpistemicTruth.VERIFIED,
            source_kind=SourceKind.DETERMINISTIC_MEASUREMENT,
            source_id="erp_poller",
        )
        gate.merge_into_subject(c2)
        state = gate.undo_engine.current_state
        self.assertIn("inventory:bay_4", state["quarantined_conflicts"])
        self.assertNotIn("inventory:bay_4", state["verified_state"])
        self.assertEqual(
            knowledge_join(EpistemicTruth.VERIFIED, EpistemicTruth.FALSIFIED),
            EpistemicTruth.CONTRADICTORY,
        )

        gate.undo_last_commit()
        restored = gate.undo_engine.current_state
        self.assertIn("inventory:bay_4", restored["verified_state"])
        self.assertTrue(gate.ledger.verify_chain())


class TestShield1FineGrainedPow(unittest.TestCase):
    def test_monomial_attack_matches_direct_and_issuer_blocks_small_d(self) -> None:
        # Prove the O(2^d * n) monomial cheat computes the EXACT same value as direct O(d*n^2) at d=4
        toy_issuer = FineGrainedOvIssuer(n=16, d=4, allow_toy_params=True)
        chal = toy_issuer.issue_challenge()
        direct = evaluate_pov(chal.u0, chal.v0)
        cheated = evaluate_pov_monomial_attack(chal.u0, chal.v0)
        self.assertEqual(direct, cheated)
        self.assertTrue(chal.toy_parameters)

        # Prove production issuer REFUSES insecure d=3 or d=4 by default
        with self.assertRaises(ValueError):
            FineGrainedOvIssuer(n=24, d=3)
        with self.assertRaises(ValueError):
            FineGrainedOvIssuer(n=36, d=4)

        # Automorphism invariance check
        u_t, v_t = apply_pov_automorphism(chal.u0, chal.v0)
        self.assertEqual(evaluate_pov(u_t, v_t), direct)

    def test_secure_d_solve_verify_forgery_replay_and_dos_resistance(self) -> None:
        # n=64 => min_secure_dimension(64) = 16 (2^16 = 65536 >> 64^2 = 4096)
        self.assertEqual(min_secure_dimension(64), 16)
        issuer = FineGrainedOvIssuer(n=16, d=16, epoch_max_verified=2, max_pending=8)
        initial_epoch = issuer.epoch_id

        # Unauthenticated challenge flood MUST NOT rotate epoch or grow _pending past max_pending
        for _ in range(30):
            issuer.issue_challenge()
        self.assertEqual(issuer.epoch_id, initial_epoch)
        self.assertLessEqual(issuer.pending_count, 8)

        # Genuine solve & verify
        chal = issuer.issue_challenge()
        self.assertFalse(chal.toy_parameters)
        sol = solve_ov_challenge(chal)
        self.assertTrue(issuer.verify_solution(sol))

        # Replay rejected
        with self.assertRaises(FineGrainedPowError):
            issuer.verify_solution(sol)

        # Forgery (+1 on 1 point) rejected
        chal2 = issuer.issue_challenge()
        sol2 = solve_ov_challenge(chal2)
        tampered = FineGrainedSolution(
            challenge_id=sol2.challenge_id,
            evaluations=((sol2.evaluations[0] + 1) % ((1 << 127) - 1),) + sol2.evaluations[1:],
        )
        with self.assertRaises(FineGrainedPowError):
            issuer.verify_solution(tampered)


class TestShield3InfoTheoreticChannel(unittest.TestCase):
    def test_roundtrip_dos_defense_crash_persistence_and_shamir_cheater(self) -> None:
        self.assertEqual(OneTimePadBook.estimate_drive_longevity_years(1.0, 500, 512), 10065.6)

        with tempfile.TemporaryDirectory() as tmpdir:
            s_store = FileBackedPadStore(os.path.join(tmpdir, "sender.json"))
            r_store = FileBackedPadStore(os.path.join(tmpdir, "receiver.json"))
            raw_pad = os.urandom(16384)
            s_pad, r_pad = OneTimePadBook.create_paired_books(
                "RVBA-PAD-TEST-01", trng_bytes=raw_pad, sender_store=s_store, receiver_store=r_store
            )
            b_s, b_r = OneTimePadBook.create_paired_books("RVBA-PAD-TEST-02", size_bytes=16384)

            alice = AlgorithmicaCivicNode("US-VA-ROA/NGO/rescue-mission")
            bob = AlgorithmicaCivicNode("US-VA-ROA/NGO/council-community-services")
            alice.install_peer_pads(bob.node_id, s_pad, b_r)
            bob.install_peer_pads(alice.node_id, b_s, r_pad)

            # 1. Attack A: 1-packet huge mac_pad_len wipe DoS MUST be rejected with 0 pad burned
            rem_before = r_pad.remaining_bytes
            wipe_env = InfoTheoreticEnvelope(
                pad_id="RVBA-PAD-TEST-01",
                sender_id=alice.node_id,
                receiver_id=bob.node_id,
                service_code="shelter.sync",
                lane="FINALIZED",
                otp_offset=0,
                otp_len=32,
                ciphertext_hex=("00" * 32),
                mac_pad_offset=r_pad.mac_start,
                mac_pad_len=1_000_000,  # Huge attacker length
                wc_tag_hex=("00" * 16),
                max_forgery_prob_bound=1e-36,
            )
            with self.assertRaises(InfoTheoreticSecurityError):
                bob.receive_envelope(wipe_env)
            self.assertEqual(r_pad.remaining_bytes, rem_before)

            # 2. Attack B: Single forged MAC on active slot MUST NOT desync legitimate packet
            claim = alice.epistemic_gate.ingest(
                claim_id="IT-001",
                subject="capacity:rescue",
                payload={"beds_open": 6},
                proposed_truth=EpistemicTruth.VERIFIED,
                source_kind=SourceKind.HUMAN_ATTESTED,
                source_id="supervisor",
            )
            # Build a forged packet targeting the exact next MAC offset first
            forged = InfoTheoreticEnvelope(
                pad_id="RVBA-PAD-TEST-01",
                sender_id=alice.node_id,
                receiver_id=bob.node_id,
                service_code="shelter.sync",
                lane="FINALIZED",
                otp_offset=0,
                otp_len=32,
                ciphertext_hex=("aa" * 32),
                mac_pad_offset=r_pad.mac_start,
                mac_pad_len=32,
                wc_tag_hex=("ff" * 16),
                max_forgery_prob_bound=1e-36,
            )
            with self.assertRaises(InfoTheoreticSecurityError):
                bob.receive_envelope(forged)
            self.assertEqual(r_pad.remaining_bytes, rem_before)  # Not wiped after 1 bad MAC!

            # Legitimate packet STILL succeeds cleanly after 1 attacker forgery attempt!
            env, snap = alice.send_claim(bob, "shelter.sync", claim, lane="FINALIZED")
            self.assertIsNotNone(snap)

            # Replay of valid envelope MUST raise PadReuseError
            with self.assertRaises(PadReuseError):
                bob.receive_envelope(env)

            # 3. Crash-recovery persistence: reload sender pad from disk & verify cursor did NOT reset to 0
            reloaded_sender = OneTimePadBook("RVBA-PAD-TEST-01", raw_pad, state_store=s_store)
            next_offset, _ = reloaded_sender.consume_next_otp(16)
            self.assertGreater(next_offset, 0)

        # 4. Shamir 3-of-5 + active-cheater Reed-Solomon detection
        anchors = ["A1", "A2", "A3", "A4", "A5"]
        secret = os.urandom(32)
        shares = ShamirQuorum.split_secret("ROA-Q1", secret, anchors, threshold_t=3)
        self.assertEqual(ShamirQuorum.reconstruct_secret([shares[0], shares[2], shares[4]]), secret)
        self.assertEqual(ShamirQuorum.reconstruct_secret(shares), secret)

        # Corrupt 4th share -> MUST raise QuorumCorruptionError when passed alongside 3 honest shares
        bad_share = WitnessShare(
            quorum_id=shares[3].quorum_id,
            anchor_name=shares[3].anchor_name,
            x_index=shares[3].x_index,
            threshold_t=shares[3].threshold_t,
            total_n=shares[3].total_n,
            secret_byte_len=shares[3].secret_byte_len,
            y_blocks=((shares[3].y_blocks[0] + 1) % ((1 << 127) - 1),) + shares[3].y_blocks[1:],
        )
        with self.assertRaises(QuorumCorruptionError):
            ShamirQuorum.reconstruct_secret([shares[0], shares[1], shares[2], bad_share])

        # Wegman-Carter rejects r == 0
        with self.assertRaises(ValueError):
            WegmanCarterMac.compute_tag(b"hello", r=0, s=123)


class TestShield2CoupledTileSim(unittest.TestCase):
    def test_order_entropy_and_differential_humidity_cancellation(self) -> None:
        self.assertAlmostEqual(MAX_UNIT_CELL_ORDER_ENTROPY_BITS, 9.169925, places=5)
        arr = CoupledTileArray("ROA-ARR-01", CMOS_28NM_SILICON, num_tiles=16)
        self.assertAlmostEqual(arr.max_raw_order_entropy_bits, 146.72, places=2)
        self.assertEqual(len(arr.raw_puf_bitstring()), 16 * 12)

        # Differential pair on FR-4 PCB: common-mode +5% humidity dielectric drift & +3% V_DD ripple
        gate = SweetbrierEpistemicGate("ROA-HW-TEST")
        exposed = CoupledTile3x3("EXP-1", PCB_FR4_COUPLED_STRIP, manufacturing_seed="board-A")
        ref = CoupledTile3x3("REF-1", PCB_FR4_COUPLED_STRIP, manufacturing_seed="board-A-ref")
        enr = DifferentialTilePair.enroll("PAIR-01", exposed, ref, ratio_tolerance=0.02)

        # Apply uniform common-mode +5% FR-4 moisture epsilon_r shift & +3% V_DD ripple to BOTH tiles
        exp_humid = exposed.with_tamper(dielectric_scale=1.05, substrate_dielectric_scale=1.05, v_dd_scale=1.03)
        ref_humid = ref.with_tamper(dielectric_scale=1.05, substrate_dielectric_scale=1.05, v_dd_scale=1.03)
        c_ok = DifferentialTilePair.attest(exp_humid, ref_humid, enr, gate, "hw-humid")
        self.assertEqual(c_ok.truth_value, EpistemicTruth.VERIFIED)

        # Apply localized +2 pF microprobe to EXPOSED tile ONLY -> MUST catch tamper (FALSIFIED)
        exp_probed = exp_humid.with_tamper(
            delta_c_probe_f=2.0e-12, dielectric_scale=1.05, substrate_dielectric_scale=1.05, v_dd_scale=1.03
        )
        c_bad = DifferentialTilePair.attest(exp_probed, ref_humid, enr, gate, "hw-probed")
        self.assertEqual(c_bad.truth_value, EpistemicTruth.FALSIFIED)


class TestLayer1XRoadSidecar(unittest.TestCase):
    def test_niis_headers_llm_clamp_and_pii_block(self) -> None:
        sidecar = XRoadEpistemicSidecar("US-VA-ROA/NGO/rescue-mission/intake")

        # Reject invalid NIIS REST path
        bad_path = XRoadRestRequest(
            method="POST",
            path="/invalid/api/v1",
            headers={"X-Road-Client": "US-VA-ROA/NGO/rescue-mission/intake"},
            json_body={"beds": 5},
        )
        with self.assertRaises(XRoadSidecarPolicyError):
            sidecar.filter_outbound_rest(
                bad_path, "beds", SourceKind.HUMAN_ATTESTED, "sup", EpistemicTruth.VERIFIED
            )

        # Block LLM self-certified VERIFIED write
        valid_req = XRoadRestRequest(
            method="POST",
            path="/r1/US-VA-ROA/NGO/ccs/shelter/updateCapacity",
            headers={"X-Road-Client": "US-VA-ROA/NGO/rescue-mission/intake"},
            json_body={"beds_open": 6, "pii_bytes": 0},
        )
        res_llm = sidecar.filter_outbound_rest(
            valid_req, "beds", SourceKind.LLM_SYNTHESIS, "agent", EpistemicTruth.VERIFIED, require_verified=True
        )
        self.assertFalse(res_llm.allowed)
        self.assertEqual(res_llm.claim.truth_value, EpistemicTruth.UNKNOWN)

        # Block PII even from human
        pii_req = XRoadRestRequest(
            method="POST",
            path="/r1/US-VA-ROA/NGO/ccs/shelter/updateCapacity",
            headers={"X-Road-Client": "US-VA-ROA/NGO/rescue-mission/intake"},
            json_body={"beds_open": 6, "ssn": "123-45-6789"},
        )
        res_pii = sidecar.filter_outbound_rest(
            pii_req, "beds", SourceKind.HUMAN_ATTESTED, "sup", EpistemicTruth.VERIFIED
        )
        self.assertFalse(res_pii.allowed)
        self.assertEqual(res_pii.lane, "BLOCKED")

        # Clear human-attested zero-PII write with X-Sweetbrier-* provenance headers
        res_ok = sidecar.filter_outbound_rest(
            valid_req, "beds", SourceKind.HUMAN_ATTESTED, "sup", EpistemicTruth.VERIFIED, require_verified=True
        )
        self.assertTrue(res_ok.allowed)
        self.assertEqual(res_ok.forwarded_request.headers["X-Sweetbrier-Truth"], "VERIFIED")
        self.assertEqual(res_ok.forwarded_request.headers["X-Road-Client"], "US-VA-ROA/NGO/rescue-mission/intake")


if __name__ == "__main__":
    unittest.main(verbosity=2)
