"""
Parameters for the 16 nm DMPPM resonant HBC transceiver (Li et al., CICC 2026).

Every number is tagged:
  [paper]  taken directly from the paper text / figures / Table 1
  [derived] computed from paper numbers (derivation in the comment)
  [assumed] not given in the paper; chosen to be physically reasonable and,
            where possible, calibrated so the model reproduces a paper result
"""
from dataclasses import dataclass, field
import math


@dataclass
class DMPPMParams:
    bits_per_pulse: int = 6            # [paper] optimum BPP ~6 (Fig. 8)
    t_min: float = 200e-9              # [paper] shortest interval (ISI / RX recovery limited)
    t_max: float = 600e-9              # [paper] longest interval (dynamic-range limited)
    gray: bool = True                  # [assumed] Gray-map symbols -> adjacent-slot error = 1 bit

    @property
    def n_slots(self) -> int:
        return 2 ** self.bits_per_pulse

    @property
    def t_slot(self) -> float:
        # [derived] 400 ns / 64 = 6.25 ns at 6 b/pulse ("total jitter limit < 6.25 ns")
        return (self.t_max - self.t_min) / self.n_slots

    @property
    def t_mean(self) -> float:
        # mean interval for uniformly distributed (scrambled) data
        return self.t_min + (self.n_slots - 1) / 2 * self.t_slot + self.t_slot / 2

    @property
    def avg_bitrate(self) -> float:
        # [derived] 6 b / ~400 ns = 15 Mb/s; 1 b / 400 ns = 2.5 Mb/s
        return self.bits_per_pulse / self.t_mean


@dataclass
class TXParams:
    L: float = 4.7e-6                  # [paper] shielded 1812 inductor, 4.7 uH
    C_load: float = 20e-12             # [paper] C_LOAD = 20 pF (Fig. 11)
    C_par_out: float = 2.0e-12         # [assumed] pad + ESD + reset-switch drain on V_OUT
    C_tune_unit: float = 127e-15       # [paper] 127 fF unit
    C_tune_bits: int = 7               # [paper] 7-bit bank -> 16.1 pF full scale
    C_tune_code: int = 16              # [assumed] nominal code; calibrated by tx_calibrate()
    Q_tune: float = 8.0                # [paper] on-chip cap Q < 10
    R_on_pass: float = 6.0             # [assumed] 250um/90nm thick-gate LVT pass-gate
    R_esr_L: float = 4.0               # [assumed] inductor ESR @ 15 MHz (Q_L ~ 110)
    R_electrode: float = 3.0           # [assumed] electrode/skin series R. With pass-gate, ESR and the
                                       #   tuning-cap ESR the effective series R is ~17 ohm, calibrated
                                       #   so resistive TX loss = 7.3 uW @ 2 Vpp, 2.5 MHz (Fig. 13)
    C_lx: float = 1.4e-12              # [assumed] V_LX node parasitic; 'other parasitic loss' 3.52uW
    R_damp: float = 1.0e3              # [assumed] passive RC damper across inductor
    C_damp: float = 0.3e-12            # [assumed]
    R_reset: float = 300.0             # [assumed] 15um cascoded reset switch
    V_TX: float = 1.0                  # [paper] 2 Vpp output at best-efficiency point (V_out = 2 V_TX)
    V_TX_max: float = 1.65             # [paper] -> 3.3 V output
    VDDH: float = 1.8                  # [paper] thick-gate domain
    C_gate_pass: float = 0.204e-12     # [derived] gate-driver 1.65 uW / (2.5 MHz * 1.8^2)
    E_dtc_per_pulse: float = 0.112e-12 # [derived] fine delay cells 0.28 uW / 2.5 MHz
    P_leak: float = 280e-9             # [paper] TX leakage ~280 nW
    f_target: float = 15e6             # [paper] resonance / "carrier" 15 MHz
    deadtime: float = 1e-9             # [assumed] pass->reset non-overlap
    t_reset: float = 150e-9            # [assumed] reset window (paper: > 200 ns available)
    dtc_lsb: float = 1e-9              # [paper] 1 ns resolution delay-line DTC
    dtc_jitter_rms: float = 30e-12     # [assumed]
    dtc_inl_rms: float = 0.15e-9       # [assumed] static INL of the delay line (per code, random)

    @property
    def C_tune(self) -> float:
        return self.C_tune_code * self.C_tune_unit

    @property
    def C_total(self) -> float:
        return self.C_load + self.C_par_out + self.C_tune

    @property
    def R_tune(self) -> float:
        # series ESR of the on-chip tuning bank: R = 1 / (w C Q)
        if self.C_tune <= 0:
            return 0.0
        return 1.0 / (2 * math.pi * self.f_target * self.C_tune * self.Q_tune)

    @property
    def R_series(self) -> float:
        # effective series R seen by the resonant current. The tuning branch carries only
        # the fraction C_tune/C_total of the current, so its ESR is weighted by that ratio^2.
        share = self.C_tune / self.C_total
        return self.R_on_pass + self.R_esr_L + self.R_electrode + self.R_tune * share ** 2

    @property
    def t_pass(self) -> float:
        # pass-gate window = one designed resonance period at f_target
        return 1.0 / self.f_target


@dataclass
class ChannelParams:
    # [paper] Fig. 10: 2 Vpp TX -> ~100 mV @90 cm, ~60 mV @120 cm, ~40 mV @150 cm
    ref_points_cm: tuple = (90.0, 120.0, 150.0)
    ref_rx_vpp: tuple = (0.100, 0.060, 0.040)
    ref_tx_vpp: float = 2.0
    f_hp: float = 100e3                # [assumed] EQS capacitive-return high-pass
    f_lp: float = 40e6                 # [assumed] body / electrode roll-off (BW~15 MHz, Fig. 11)
    echo_delay: float = 60e-9          # [paper-ish] TX2 multipath second peak after main pulse
    echo_gain: float = 0.0             # set >0 to enable multipath
    amp_var_sigma: float = 0.10        # [assumed] per-pulse amplitude variation (motion, LC parasitics)
    mains_vpp: float = 0.05            # [assumed] 50/60 Hz pickup at RX input
    mains_f: float = 60.0
    env_noise_rms: float = 0.0         # extra environmental white noise at RX input (V rms)


@dataclass
class RXParams:
    fs: float = 2e9                    # simulation sample rate (0.5 ns)
    # input coupling network [paper] 1.62 pF / 120 kOhm  -> fc = 819 kHz
    C_in: float = 1.62e-12
    R_in: float = 120e3
    # amplifier stages (single-pole, gain/BW) [assumed values within paper's 2-7.5x range]
    g_s0: float = 2.78                 # [calibrated] sized for <1e-3 false pulses/symbol (calibrate.py)
    g_s1: float = 2.78
    g_s2: float = 4.0
    bw_amp: float = 60e6               # [assumed] per-stage bandwidth (4x the 15 MHz pulse)
    f_diff: float = 15e6               # [paper] HPF differentiator tuned to TX frequency
    f_lpf: float = 30e6                # [assumed] tunable LPF before S3
    en_in: float = 213e-9              # [calibrated] input-referred noise density (V/rtHz) that gives
                                       #   the paper's -47 dBm sensitivity @ 6 b/p (calibrate.py)
    offset_3sigma: float = 1.0e-3      # [paper] MC 3-sigma input-referred offset < 1 mV
    # detectors
    vth_coarse: float = 50e-3          # [paper] coarse threshold 50 mV below fine (at S1 output)
    oneshot: float = 100e-9            # [paper] RC one-shot, 100 ns
    t_wake: float = 20e-9              # [paper] fine detector wakes in < 20 ns
    fine_cmp_noise: float = 0.3e-3     # [assumed] fine comparator input noise (V rms at S3 in)
    diff_penalty_db: float = -1.94     # system model only. Paper quotes ~3 dB; this is the value
                                       #   back-annotated from the block chain (calibrate.py), relative
                                       #   to sigma = e_n*sqrt(pi/2*f_lpf) / (A*w0/2)
    threshold_mode_vth: float = 0.5    # for 'threshold' (no-differentiator) RX, fraction of nominal peak
    # TDC (GRO coarse-fine, 0.4 V) [assumed resolution; paper gives architecture only]
    tdc_lsb: float = 0.25e-9
    tdc_jitter_k: float = 6.25e-15     # [assumed] GRO accumulated jitter sigma = sqrt(k*T): 50 ps rms @ 400 ns
    tdc_gain_mismatch: float = 0.002   # gain mismatch between the two interleaved TDCs
    tdc_scale_err: float = 0.0         # common GRO gain error (PVT); 0 = the paper's nominal
    # power [paper Fig. 13 / text]
    P_s0: float = 10.5e-6
    P_s1: float = 10.5e-6
    P_s2: float = 6.3e-6
    P_s3_on: float = 20e-6             # [paper] 20 uW continuous-time comparator, power-gated
    P_tdc: float = 15.67e-6            # [paper] at 2.5 MHz conversion rate
    P_misc: float = 2.6e-6             # [derived] Table 48 uW - Fig.13 45.4 uW (bias, coarse cmp, FIFO)


@dataclass
class SystemParams:
    dmppm: DMPPMParams = field(default_factory=DMPPMParams)
    tx: TXParams = field(default_factory=TXParams)
    ch: ChannelParams = field(default_factory=ChannelParams)
    rx: RXParams = field(default_factory=RXParams)
    seed: int = 1


def vpp_to_dbm(vpp: float, r: float = 8e3) -> float:
    """Paper's sensitivity convention: input matched to 1 pF @ 20 MHz (~8 kOhm), sine-equivalent rms.
    Check: 35 mVpp -> -47 dBm, 7.9 mVpp -> -60 dBm (paper: -61)."""
    vrms = vpp / (2 * math.sqrt(2))
    return 10 * math.log10(vrms ** 2 / r / 1e-3)


def dbm_to_vpp(dbm: float, r: float = 8e3) -> float:
    p = 1e-3 * 10 ** (dbm / 10)
    return math.sqrt(p * r) * 2 * math.sqrt(2)
