#!/usr/bin/env python3
"""
ONE BIG BACKEND — SHIELD 2: LUMPED-ELEMENT CAPACITIVE TAMPER CELL MODEL (v2 HONEST SPEC)
(`obb_coupled_tile_sim.py`)
License: GNU AGPLv3
External Dependencies: 0 (100% Python Standard Library + local `obb_primitives` & `obb_epistemic_lattice`)

SCOPE & HONESTY NOTICE:
  This module is a LUMPED-ELEMENT CAPACITIVE/INDUCTIVE PHYSICS MODEL (pre-silicon / pre-PCB
  simulation) — NOT a 3D electromagnetic field solver or tapeout-verified silicon PUF.

v2 Physics & Entropy Corrections (vs. v1):
  1. EXACT ORDER-ENTROPY ACCOUNTING: Comparing 4 cardinal edges pairwise yields 6 bits,
     but transitivity restricts valid rankings to 4! = 24 (log2(24) = 4.585 bits). Across
     4 edges + 4 corners, one 3x3 unit cell provides AT MOST log2(24^2) = 9.17 bits of
     pairwise-order min-entropy (576 valid rankings, NOT 4,096). `CoupledTileArray` models
     tiling M >= 16 independent cells (~146.7 bits raw order entropy) for a hardware root.
  2. RATIOMETRIC DIFFERENTIAL SENSING (`DifferentialTilePair`): Absolute mV thresholds
     derived from kT/C alone ignore 28nm comparator offset mismatch (5-20 mV pre-trim),
     reset-switch charge injection, V_DD ripple, and FR-4 PCB ambient humidity/temperature
     dielectric drift (2-5%+). Comparing an exposed surface tamper tile against an adjacent
     buried reference tile cancels common-mode V_DD and ambient epsilon_r drift while
     preserving sensitivity to localized invasive probe Delta-C_probe loading.
"""

from __future__ import annotations

import hashlib
import math
from dataclasses import dataclass
from typing import List, Optional, Sequence, Tuple

from obb_epistemic_lattice import (
    EpistemicClaim,
    EpistemicTruth,
    SourceKind,
    SweetbrierEpistemicGate,
)
from obb_primitives import canonical_sha256

BOLTZMANN_K_J_PER_K: float = 1.380649e-23
EDGE_INDICES: Tuple[int, ...] = (1, 3, 5, 7)
DIAG_INDICES: Tuple[int, ...] = (0, 2, 4, 6)
MAX_UNIT_CELL_ORDER_ENTROPY_BITS: float = 2.0 * math.log2(math.factorial(4))  # 9.169925 bits


@dataclass(frozen=True)
class TileFabricationSpec:
    name: str
    v_dd_v: float
    rise_time_s: float
    c_edge_f: float
    c_diag_f: float
    c_gnd_f: float
    m_edge_h: float
    m_diag_h: float
    i_drive_a: float
    temperature_k: float
    v_il_frac: float
    v_ih_frac: float
    die_variation_pct: float
    # Realistic non-thermal noise/offset floor for honest hardware budgeting
    comparator_offset_mv: float


CMOS_28NM_SILICON = TileFabricationSpec(
    name="CMOS_28NM_SILICON_LUMPED_MODEL",
    v_dd_v=1.0,
    rise_time_s=50e-12,
    c_edge_f=2.5e-15,
    c_diag_f=1.0e-15,
    c_gnd_f=4.0e-15,
    m_edge_h=0.05e-12,
    m_diag_h=0.02e-12,
    i_drive_a=100e-6,
    temperature_k=300.0,
    v_il_frac=0.30,
    v_ih_frac=0.52,
    die_variation_pct=0.03,
    comparator_offset_mv=5.0,  # Typical 28nm pre-trim offset floor
)

PCB_FR4_COUPLED_STRIP = TileFabricationSpec(
    name="PCB_FR4_COUPLED_STRIP_LUMPED_MODEL",
    v_dd_v=3.3,
    rise_time_s=1.5e-9,
    c_edge_f=0.8e-12,
    c_diag_f=0.25e-12,
    c_gnd_f=1.5e-12,
    m_edge_h=1.8e-9,
    m_diag_h=0.5e-9,
    i_drive_a=25e-3,
    temperature_k=300.0,
    v_il_frac=0.30,
    v_ih_frac=0.52,
    die_variation_pct=0.04,
    comparator_offset_mv=2.0,
)


@dataclass(frozen=True)
class TileReadout:
    byte_value: int
    v_cap_v: float
    i_cap_a: float
    v_ind_peak_v: float
    v_total_peak_v: float
    thermal_noise_rms_v: float
    snr_db: float
    efficiency: float
    conservation_ok: bool
    carrier_state: str
    epistemic: EpistemicTruth


class CoupledTile3x3:
    """
    Lumped-element 3x3 floating-node capacitive/inductive unit cell.
    Assumes a pre-evaluation reset switch discharges the center node to 0 V before each byte.
    """

    def __init__(
        self,
        tile_id: str,
        spec: TileFabricationSpec,
        manufacturing_seed: str = "wafer-default",
        delta_c_probe_f: float = 0.0,
        dielectric_scale: float = 1.0,
        v_dd_scale: float = 1.0,
        substrate_dielectric_scale: float = 1.0,
    ) -> None:
        if delta_c_probe_f < 0.0:
            raise ValueError("delta_c_probe_f cannot be negative.")
        if dielectric_scale <= 0.0 or v_dd_scale <= 0.0 or substrate_dielectric_scale <= 0.0:
            raise ValueError("Physical scaling factors must be strictly positive.")

        self.tile_id = tile_id
        self.spec = spec
        self.manufacturing_seed = manufacturing_seed
        self.delta_c_probe_f = float(delta_c_probe_f)
        self.dielectric_scale = float(dielectric_scale)
        self.v_dd_scale = float(v_dd_scale)
        self.substrate_dielectric_scale = float(substrate_dielectric_scale)

        self._c_m: Tuple[float, ...] = tuple(
            self._varied_param(
                base=spec.c_edge_f if i in EDGE_INDICES else spec.c_diag_f,
                tag=f"CM:{i}",
            )
            * self.dielectric_scale
            for i in range(8)
        )
        self._m_mut: Tuple[float, ...] = tuple(
            self._varied_param(
                base=spec.m_edge_h if i in EDGE_INDICES else spec.m_diag_h,
                tag=f"M:{i}",
            )
            for i in range(8)
        )
        self._c_gnd: float = (
            self._varied_param(base=spec.c_gnd_f, tag="CGND") * self.substrate_dielectric_scale
        )

    def _varied_param(self, base: float, tag: str) -> float:
        digest = hashlib.sha256(f"{self.tile_id}:{self.manufacturing_seed}:{tag}".encode("utf-8")).digest()
        raw = int.from_bytes(digest[:4], "big") / (2**32 - 1)
        skew = (raw * 2.0 - 1.0) * self.spec.die_variation_pct
        return base * (1.0 + skew)

    @property
    def c_total_f(self) -> float:
        return self._c_gnd + self.delta_c_probe_f + sum(self._c_m)

    @property
    def thermal_noise_rms_v(self) -> float:
        """Theoretical Johnson-Nyquist kT/C floor only (excludes offset/flicker/PVT drift)."""
        return math.sqrt((BOLTZMANN_K_J_PER_K * self.spec.temperature_k) / self.c_total_f)

    def with_tamper(
        self,
        delta_c_probe_f: float = 0.0,
        dielectric_scale: float = 1.0,
        v_dd_scale: float = 1.0,
        substrate_dielectric_scale: float = 1.0,
    ) -> "CoupledTile3x3":
        return CoupledTile3x3(
            tile_id=self.tile_id,
            spec=self.spec,
            manufacturing_seed=self.manufacturing_seed,
            delta_c_probe_f=delta_c_probe_f,
            dielectric_scale=dielectric_scale,
            v_dd_scale=v_dd_scale,
            substrate_dielectric_scale=substrate_dielectric_scale,
        )

    def evaluate_byte(self, byte_value: int) -> TileReadout:
        if not (0 <= byte_value <= 255):
            raise ValueError(f"byte_value must be in 0..255, got {byte_value}.")

        v_dd = self.spec.v_dd_v * self.v_dd_scale
        bits = tuple((byte_value >> i) & 1 for i in range(8))
        c_active = sum(self._c_m[i] for i in range(8) if bits[i] == 1)
        c_inactive = sum(self._c_m[i] for i in range(8) if bits[i] == 0)
        c_b = self._c_gnd + self.delta_c_probe_f + c_inactive
        c_tot = c_active + c_b

        v_cap = (c_active / c_tot) * v_dd
        i_cap = c_active * (v_dd / self.spec.rise_time_s)
        m_active = sum(self._m_mut[i] for i in range(8) if bits[i] == 1)
        v_ind_peak = m_active * (self.spec.i_drive_a / self.spec.rise_time_s)
        v_total_peak = v_cap + v_ind_peak

        if c_active > 0.0:
            c_eq = (c_active * c_b) / c_tot
            e_driver = c_eq * (v_dd**2)
            e_center = 0.5 * c_b * (v_cap**2)
            efficiency = e_center / e_driver
            conservation_ok = (0.0 <= efficiency < 0.5) and (e_center < e_driver)
        else:
            efficiency = 0.0
            conservation_ok = True

        v_noise = self.thermal_noise_rms_v
        snr_db = 20.0 * math.log10(v_total_peak / v_noise) if v_total_peak > 0.0 else float("-inf")

        v_il = self.spec.v_il_frac * v_dd
        v_ih = self.spec.v_ih_frac * v_dd
        if not conservation_ok:
            carrier_state, epistemic = "LOW", EpistemicTruth.FALSIFIED
        elif v_total_peak >= v_ih:
            carrier_state, epistemic = "HIGH", EpistemicTruth.VERIFIED
        elif v_total_peak <= v_il:
            carrier_state, epistemic = "LOW", EpistemicTruth.FALSIFIED
        else:
            carrier_state, epistemic = "INDETERMINATE", EpistemicTruth.UNKNOWN

        return TileReadout(
            byte_value=byte_value,
            v_cap_v=v_cap,
            i_cap_a=i_cap,
            v_ind_peak_v=v_ind_peak,
            v_total_peak_v=v_total_peak,
            thermal_noise_rms_v=v_noise,
            snr_db=snr_db,
            efficiency=efficiency,
            conservation_ok=conservation_ok,
            carrier_state=carrier_state,
            epistemic=epistemic,
        )

    def pairwise_order_bits(self) -> str:
        """
        12 pairwise comparisons (6 edge pairs + 6 corner pairs) carrying at most
        log2(4! * 4!) = 9.17 bits of true order min-entropy per unit cell.
        """
        single_v = [self.evaluate_byte(1 << i).v_total_peak_v for i in range(8)]
        bits: List[str] = []
        for group in (EDGE_INDICES, DIAG_INDICES):
            for a in range(len(group)):
                for b in range(a + 1, len(group)):
                    bits.append("1" if single_v[group[a]] > single_v[group[b]] else "0")
        return "".join(bits)


@dataclass(frozen=True)
class DifferentialEnrollment:
    pair_id: str
    spec_name: str
    challenge_bytes: Tuple[int, ...]
    enrolled_ratios: Tuple[float, ...]
    ratio_tolerance: float
    signature_hash: str


class DifferentialTilePair:
    """
    Ratiometric differential tamper sensor: compares an exposed surface tile against a
    buried/shielded reference tile on the same substrate (`R = V_exposed / V_reference`).
    Cancels common-mode V_DD ripple and ambient FR-4/CMOS uniform dielectric drift while
    staying strongly sensitive to localized invasive microprobe Delta-C_probe or top decapsulation.
    """

    BASIS_BYTES: Tuple[int, ...] = tuple(1 << i for i in range(8)) + (0xAA, 0x55, 0xFF)

    @classmethod
    def enroll(
        cls,
        pair_id: str,
        exposed_tile: CoupledTile3x3,
        reference_tile: CoupledTile3x3,
        ratio_tolerance: float = 0.02,
    ) -> DifferentialEnrollment:
        ratios = tuple(
            round(
                exposed_tile.evaluate_byte(b).v_cap_v / reference_tile.evaluate_byte(b).v_cap_v,
                6,
            )
            for b in cls.BASIS_BYTES
        )
        sig = canonical_sha256(
            {
                "pair_id": pair_id,
                "spec": exposed_tile.spec.name,
                "ratios": list(ratios),
                "ratio_tolerance": ratio_tolerance,
            }
        )
        return DifferentialEnrollment(
            pair_id=pair_id,
            spec_name=exposed_tile.spec.name,
            challenge_bytes=cls.BASIS_BYTES,
            enrolled_ratios=ratios,
            ratio_tolerance=ratio_tolerance,
            signature_hash=sig,
        )

    @classmethod
    def attest(
        cls,
        exposed_tile: CoupledTile3x3,
        reference_tile: CoupledTile3x3,
        enrollment: DifferentialEnrollment,
        epistemic_gate: SweetbrierEpistemicGate,
        claim_id: str,
    ) -> EpistemicClaim:
        obs_ratios = [
            exposed_tile.evaluate_byte(b).v_cap_v / reference_tile.evaluate_byte(b).v_cap_v
            for b in enrollment.challenge_bytes
        ]
        max_rel_dev = max(
            abs(obs - exp) / max(exp, 1e-9)
            for obs, exp in zip(obs_ratios, enrollment.enrolled_ratios)
        )
        conservation_ok = all(
            exposed_tile.evaluate_byte(b).conservation_ok and reference_tile.evaluate_byte(b).conservation_ok
            for b in enrollment.challenge_bytes
        )
        intact = conservation_ok and (max_rel_dev <= enrollment.ratio_tolerance)
        payload = {
            "pair_id": enrollment.pair_id,
            "model_scope": "LUMPED_ELEMENT_PRE_SILICON_SIMULATION",
            "max_ratiometric_deviation": round(max_rel_dev, 6),
            "ratio_tolerance": enrollment.ratio_tolerance,
            "conservation_verified": conservation_ok,
            "hardware_integrity": "INTACT" if intact else "TAMPER_DETECTED",
        }
        return epistemic_gate.ingest(
            claim_id=claim_id,
            subject=f"hardware:diff_tile:{enrollment.pair_id}",
            payload=payload,
            proposed_truth=EpistemicTruth.VERIFIED if intact else EpistemicTruth.FALSIFIED,
            source_kind=SourceKind.HARDWARE_PUF,
            source_id=f"LUMPED_DIFF:{enrollment.pair_id}",
            note=f"Ratiometric deviation={max_rel_dev:.4f} (tol={enrollment.ratio_tolerance:.4f}).",
        )


class CoupledTileArray:
    """
    Array of M independent 3x3 unit cells (each contributing <= 9.17 bits of order entropy).
    Example: M = 16 tiles => <= 146.7 bits raw pairwise-order entropy (pre-fuzzy-extractor).
    """

    def __init__(
        self,
        array_id: str,
        spec: TileFabricationSpec,
        num_tiles: int = 16,
        manufacturing_seed: str = "wafer-default",
    ) -> None:
        if num_tiles < 1:
            raise ValueError("num_tiles must be >= 1.")
        self.array_id = array_id
        self.tiles = tuple(
            CoupledTile3x3(
                tile_id=f"{array_id}:T{i:02d}",
                spec=spec,
                manufacturing_seed=manufacturing_seed,
            )
            for i in range(num_tiles)
        )

    @property
    def max_raw_order_entropy_bits(self) -> float:
        return round(len(self.tiles) * MAX_UNIT_CELL_ORDER_ENTROPY_BITS, 2)

    def raw_puf_bitstring(self) -> str:
        return "".join(t.pairwise_order_bits() for t in self.tiles)
