"""
(1) INDEPENDENT SYSTEM-LEVEL MODEL

Closed-form / statistical model of the whole link. It does not simulate any waveform
and does not import any block model. Every block is reduced to a few equations:

  TX energy   : E_R = pi R C^1.5 V^2 / (4 sqrt L)  (RLC loss; V = 2 V_TX)
                + C_lx V_TX^2 (LX-node parasitic) + C_g VDDH^2 (gate drive) + E_dtc
                + residual energy when the tank is detuned from the pass window
  Channel     : log-linear path loss in dB/cm fitted to the paper's Fig. 10 points
  RX noise    : sigma_v = e_n * sqrt(ENBW)
  Timing      : sigma_t = penalty * sigma_v / (A w0 / 2)   (slope of the raised cosine,
                penalty = 3 dB for the peak-to-zero-crossing differentiator)
  Detection   : P_miss = Q((A - V_th) / sigma),  false alarms from Rice's level-crossing rate
  Symbol error: P(|interval error| > t_slot/2) with Gaussian jitter (+ uniform DTC rounding)
  Energy/bit  : power / throughput; plus the BPP optimisation model of Fig. 8

It also provides a fast symbol-level Monte Carlo (simulate_symbols) built from the same
abstract statistics.
"""
from __future__ import annotations
import math
from dataclasses import dataclass
import numpy as np
from scipy.special import erfc

from .params import SystemParams, vpp_to_dbm, dbm_to_vpp
from . import dmppm


def qfunc(x):
    return 0.5 * erfc(np.asarray(x) / math.sqrt(2))


@dataclass
class LinkResult:
    rx_vpp: float
    sigma_t: float
    sigma_interval: float
    p_timing: float
    p_miss: float
    p_false: float
    p_sym: float
    ber: float


class SystemModel:
    def __init__(self, p: SystemParams | None = None, baseline_wander: bool = True):
        self.p = p or SystemParams()
        # Back-annotated from the block-level simulation: the 819 kHz AC-coupled input removes
        # the pulse train's DC content, so the RX baseline sits below zero (on average -A*T0/(2*t_mean),
        # ~ -8% of A), deepest right after a pulse and recovering with tau = R_in*C_in. This lowers
        # the pulse height above the coarse threshold and pushes the noise away from it between
        # pulses (fewer false alarms, mostly late in long intervals). False -> the naive model.
        self.baseline_wander = baseline_wander

    # ------------------------------------------------------------------ TX
    def tx_energy_per_pulse(self, V_TX: float | None = None, C_total: float | None = None) -> dict:
        tx = self.p.tx
        V_TX = tx.V_TX if V_TX is None else V_TX
        C_nom = tx.C_total
        C = C_nom if C_total is None else C_total
        L, R = tx.L, tx.R_series
        V = 2 * V_TX
        e_res = math.pi * R * C ** 1.5 * V ** 2 / (4 * math.sqrt(L))
        e_par = tx.C_lx * V_TX ** 2
        e_gate = tx.C_gate_pass * tx.VDDH ** 2
        e_dtc = tx.E_dtc_per_pulse
        e_detune = self.detune_energy(V_TX, C)
        return dict(resistive=e_res, parasitic=e_par, gate=e_gate, dtc=e_dtc,
                    detune=e_detune, total=e_res + e_par + e_gate + e_dtc + e_detune)

    def detune_energy(self, V_TX: float, C: float) -> float:
        """Energy left in the tank when Pass opens after the fixed window T0 = 1/f_target.
        Lossless approximation: v(T0) = V_TX (1 - cos w T0), i(T0) = C V_TX w sin(w T0);
        that energy is dumped by the reset switch / damper."""
        tx = self.p.tx
        w = 1 / math.sqrt(tx.L * C)
        T0 = tx.t_pass
        v = V_TX * (1 - math.cos(w * T0))
        i = C * V_TX * w * math.sin(w * T0)
        return 0.5 * C * v ** 2 + 0.5 * tx.L * i ** 2

    def cmos_energy_per_pulse(self, V: float) -> float:
        # Fig. 2, CMOS driver: P = C V^2 f / 2
        return self.p.tx.C_total * V ** 2 / 2

    def tx_power(self, pulse_rate: float | None = None, V_TX: float | None = None) -> dict:
        pr = pulse_rate or 1 / self.p.dmppm.t_mean
        e = self.tx_energy_per_pulse(V_TX)
        out = {k: v * pr for k, v in e.items()}
        out["leakage"] = self.p.tx.P_leak
        out["total"] = out["total"] + self.p.tx.P_leak
        return out

    # ------------------------------------------------------------- channel
    def channel_gain_db(self, d_cm):
        """Least-squares straight line in dB vs distance through the Fig. 10 points."""
        ch = self.p.ch
        d = np.array(ch.ref_points_cm)
        g = 20 * np.log10(np.array(ch.ref_rx_vpp) / ch.ref_tx_vpp)
        slope, icpt = np.polyfit(d, g, 1)
        return slope * np.asarray(d_cm) + icpt

    def rx_vpp_at(self, d_cm, V_TX=None):
        V_TX = self.p.tx.V_TX if V_TX is None else V_TX
        return 2 * V_TX * 10 ** (self.channel_gain_db(d_cm) / 20)

    # ------------------------------------------------------------------ RX
    def rx_noise_sigma(self) -> tuple[float, float]:
        """(sigma at fine/timing path, sigma at coarse detector), input-referred."""
        rx = self.p.rx
        enbw_fine = math.pi / 2 * rx.f_lpf                # dominant pole of timing path
        enbw_coarse = math.pi / 4 * rx.bw_amp             # two identical poles S0, S1
        return rx.en_in * math.sqrt(enbw_fine), rx.en_in * math.sqrt(enbw_coarse)

    def rx_power(self, pulse_rate: float | None = None) -> dict:
        rx = self.p.rx
        pr = pulse_rate or 1 / self.p.dmppm.t_mean
        duty = min(1.0, rx.oneshot * pr)       # S3 is on for one one-shot window per pulse
        out = dict(amp_s0=rx.P_s0, amp_s1=rx.P_s1, amp_s2=rx.P_s2,
                   amp_s3=rx.P_s3_on * duty, tdc=rx.P_tdc * pr / 2.5e6, misc=rx.P_misc)
        out["total"] = sum(out.values())
        return out

    def timing_sigma(self, rx_vpp: float, mode: str = "zero_cross") -> float:
        """Single-edge timing jitter (s) at the RX for a raised-cosine pulse of rx_vpp."""
        w0 = 2 * math.pi * self.p.tx.f_target
        sig_fine, _ = self.rx_noise_sigma()
        slope = rx_vpp * w0 / 2                        # max slope of (A/2)(1 - cos w t)
        if mode == "zero_cross":
            return 10 ** (self.p.rx.diff_penalty_db / 20) * sig_fine / slope
        # fixed threshold: noise jitter (no penalty) + walk error from amplitude variation
        return math.hypot(sig_fine / slope, self.walk_error_sigma())

    def walk_error_sigma(self, n: int = 20000) -> float:
        """Fixed-threshold comparator: crossing time t = acos(1 - 2 Vth/A)/w moves with A."""
        ch, rx = self.p.ch, self.p.rx
        w0 = 2 * math.pi * self.p.tx.f_target
        rng = np.random.default_rng(0)
        a = np.exp(rng.normal(0, ch.amp_var_sigma, n))   # relative amplitude
        f = rx.threshold_mode_vth / a                     # threshold as fraction of actual peak
        f = np.clip(f, 0, 1)
        t = np.arccos(1 - 2 * f) / w0
        return float(np.std(t))

    def interval_sigma(self, rx_vpp: float, mode: str = "zero_cross") -> float:
        tx, rx, dm = self.p.tx, self.p.rx, self.p.dmppm
        s_rx = self.timing_sigma(rx_vpp, mode)
        s_tdc = math.sqrt(rx.tdc_lsb ** 2 / 6 + rx.tdc_jitter_k * dm.t_mean)
        s_dtc = math.sqrt(2) * math.hypot(tx.dtc_jitter_rms, tx.dtc_inl_rms)
        # interleaved-TDC gain mismatch: the two TDCs read +-mismatch/2 * interval
        s_mm = rx.tdc_gain_mismatch / 2 * dm.t_mean
        return math.sqrt(2 * s_rx ** 2 + s_tdc ** 2 + s_dtc ** 2 + s_mm ** 2)

    def p_timing_error(self, sigma_int: float) -> float:
        """P(|e| > t_slot/2) where e = Gaussian(sigma_int) + DTC rounding error.
        The DTC rounds each absolute pulse time to 1 ns, so the interval error from rounding
        is the difference of two uniform(-LSB/2, LSB/2) variables (triangular, +-LSB)."""
        dm, tx = self.p.dmppm, self.p.tx
        h = dm.t_slot / 2
        lsb = tx.dtc_lsb
        u = np.linspace(-lsb, lsb, 401)
        pdf = (lsb - np.abs(u)) / lsb ** 2
        pdf /= np.trapezoid(pdf, u)
        pe = qfunc((h - u) / sigma_int) + qfunc((h + u) / sigma_int)
        return float(np.trapezoid(pe * pdf, u))

    def detection_probs(self, rx_vpp: float) -> tuple[float, float]:
        """(P_miss per pulse, P_false per symbol interval).
        The coarse threshold sees the AC-coupled baseline, which depends on the time since the
        last pulse (baseline_at). P_false integrates the Rice crossing rate over each idle span,
        averaged over the uniformly distributed DMPPM intervals; P_miss uses the baseline the
        next pulse starts from."""
        rx, ch, dm = self.p.rx, self.p.ch, self.p.dmppm
        _, sig_c = self.rx_noise_sigma()
        vth_in = rx.vth_coarse / (rx.g_s0 * rx.g_s1)
        intervals = dm.t_min + (np.arange(16) + 0.5) / 16 * (dm.t_max - dm.t_min)
        # average P_miss over the per-pulse amplitude variation and the preceding interval
        z = np.linspace(-4, 4, 81)
        a = rx_vpp * np.exp(z * ch.amp_var_sigma)
        wgt = np.exp(-z ** 2 / 2)
        wgt /= wgt.sum()
        p_miss = float(np.mean([np.sum(wgt * qfunc((a - self.baseline_at(rx_vpp, d) - vth_in) / sig_c))
                                for d in intervals]))
        # Rice: up-crossing rate nu = nu0 exp(-u^2 / 2 sigma^2), nu0 = sqrt(m2/m0).
        # For two cascaded identical poles at f_c, m2/m0 = f_c^2  ->  nu0 = f_c.
        p_false = []
        for d in intervals:
            t = np.linspace(rx.oneshot, max(d, rx.oneshot), 64)
            rate = rx.bw_amp * np.exp(-(vth_in + self.baseline_at(rx_vpp, t)) ** 2 / (2 * sig_c ** 2))
            p_false.append(1 - math.exp(-np.trapezoid(rate, t)))
        return p_miss, float(np.mean(p_false))

    def baseline_at(self, rx_vpp: float, t):
        """Depth of the AC-coupled baseline t seconds after a pulse (back-annotated from the block
        simulation). Each pulse (raised-cosine area A*T0/2) leaves a tail (A*T0/2tau) e^(-t/tau)
        through the R_in*C_in high-pass; summed over a train at mean spacing t_mean:
            b(t) = A T0 / (2 tau) * e^(-t/tau) / (1 - e^(-t_mean/tau)),
        whose time average is A*T0/(2*t_mean). Near the end of a long interval the baseline has
        recovered toward zero, which is where false pulses happen."""
        if not self.baseline_wander:
            return 0.0 * np.asarray(t)
        tau = self.p.rx.R_in * self.p.rx.C_in
        T0, tm = 1 / self.p.tx.f_target, self.p.dmppm.t_mean
        return rx_vpp * T0 / (2 * tau) * np.exp(-np.asarray(t) / tau) / (1 - math.exp(-tm / tau))

    def baseline_shift(self, rx_vpp: float) -> float:
        """Time-averaged baseline: the DC of the pulse train removed by the AC-coupled input."""
        if not self.baseline_wander:
            return 0.0
        return rx_vpp * (1 / self.p.tx.f_target) / (2 * self.p.dmppm.t_mean)

    def link(self, rx_vpp: float, mode: str = "zero_cross") -> LinkResult:
        dm = self.p.dmppm
        s_t = self.timing_sigma(rx_vpp, mode)
        s_i = self.interval_sigma(rx_vpp, mode)
        p_t = self.p_timing_error(s_i)
        p_m, p_f = self.detection_probs(rx_vpp)
        p_det = min(1.0, 2 * p_m + 2 * p_f)   # a missed / false pulse corrupts 2 intervals
        p_sym = 1 - (1 - p_t) * (1 - p_det)
        # timing errors land in the neighbouring slot -> 1 bit (Gray); detection errors -> random
        bits_t = 1.0 if dm.gray else dm.bits_per_pulse / 2
        ber = (p_t * bits_t + p_det * dm.bits_per_pulse / 2) / dm.bits_per_pulse
        return LinkResult(rx_vpp, s_t, s_i, p_t, p_m, p_f, p_sym, min(ber, 0.5))

    def sensitivity(self, ber_target: float = 1e-3, mode: str = "zero_cross") -> float:
        """Smallest RX Vpp meeting the BER target (bisection in log amplitude)."""
        lo, hi = 1e-4, 2.0
        for _ in range(60):
            mid = math.sqrt(lo * hi)
            if self.link(mid, mode).ber > ber_target:
                lo = mid
            else:
                hi = mid
        return hi

    # ---------------------------------------------------- system summary
    def summary(self) -> dict:
        dm = self.p.dmppm
        rate = dm.avg_bitrate
        tx = self.tx_power()
        rx = self.rx_power()
        s = self.sensitivity()
        return dict(bitrate=rate, tx_power=tx["total"], rx_power=rx["total"],
                    tx_pj_per_bit=tx["total"] / rate * 1e12,
                    rx_pj_per_bit=rx["total"] / rate * 1e12,
                    link_pj_per_bit=(tx["total"] + rx["total"]) / rate * 1e12,
                    sensitivity_vpp=s, sensitivity_dbm=vpp_to_dbm(s),
                    tx_breakdown=tx, rx_breakdown=rx,
                    resonant_vs_cmos=self.tx_energy_per_pulse()["resistive"]
                    / self.cmos_energy_per_pulse(2 * self.p.tx.V_TX),
                    Q=math.sqrt(self.p.tx.L / self.p.tx.C_total) / self.p.tx.R_series)

    # ------------------------------------------- Fig. 8 BPP optimisation
    def energy_vs_bpp(self, bpp=np.arange(1, 9), pulse_rate: float = 2.5e6,
                      design_bpp: int = 6) -> dict:
        """Energy per bit vs bits/pulse at a fixed pulse rate.
        TX: fixed energy per pulse -> K_TX / DR.
        RX: a static floor (bias, TDC, leakage) plus the timing-critical amplifier power.
            The slot width halves per extra bit, so sigma_t must halve; amplifier noise power
            ~ 1/P, so the timing-critical power scales as 4^DR = 2^(2 DR) (Fig. 8)."""
        bpp = np.asarray(bpp, dtype=float)
        e_tx_pulse = self.tx_energy_per_pulse()["total"]
        rx = self.rx_power(pulse_rate)
        p_crit_ref = rx["amp_s0"] + rx["amp_s1"] + rx["amp_s2"] + rx["amp_s3"]
        p_floor = rx["total"] - p_crit_ref
        p_crit = p_crit_ref * 4.0 ** (bpp - design_bpp)
        e_tx = e_tx_pulse / bpp
        e_rx = (p_floor + p_crit) / (pulse_rate * bpp)
        tot = e_tx + e_rx
        return dict(bpp=bpp, tx=e_tx, rx=e_rx, total=tot, opt=float(bpp[np.argmin(tot)]))

    # --------------------------------------------------- Fig. 3 spectra
    @staticmethod
    def pulse_spectra(f0: float = 15e6, fs: float = 20e9, nfft: int = 1 << 18) -> dict:
        """Spectra of square / 4-level staircase / raised-cosine pulses of equal amplitude
        and equal main-lobe width (Fig. 3)."""
        T = 1 / f0
        t = np.arange(-2 * T, 2 * T, 1 / fs)
        cos_p = np.where(np.abs(t) < T / 2, 0.5 * (1 + np.cos(2 * np.pi * t / T)), 0.0)
        sq = np.where(np.abs(t) < T / 4, 1.0, 0.0)
        stair = np.zeros_like(t)
        for k, lvl in enumerate([0.25, 0.5, 0.75, 1.0]):
            w = T / 2 - k * T / 8
            stair = np.where(np.abs(t) < w, lvl, stair)
        f = np.fft.rfftfreq(nfft, 1 / fs)
        out = dict(f=f)
        for name, x in dict(square=sq, staircase=stair, cosine=cos_p).items():
            X = np.abs(np.fft.rfft(x, nfft))
            out[name] = 20 * np.log10(X / X.max() + 1e-12)
        return out

    # ------------------------------------------ symbol-level Monte Carlo
    def simulate_symbols(self, n_sym: int, rx_vpp: float, mode: str = "zero_cross",
                         seed: int | None = None) -> dict:
        """Symbol-level Monte Carlo with the abstract statistics above (no waveforms)."""
        dm, tx = self.p.dmppm, self.p.tx
        rng = np.random.default_rng(self.p.seed if seed is None else seed)
        bits = rng.integers(0, 2, n_sym * dm.bits_per_pulse)
        sym = dmppm.bits_to_symbols(bits, dm)
        t_ideal = dmppm.pulse_times(sym, dm)
        t_tx = np.round(t_ideal / tx.dtc_lsb) * tx.dtc_lsb       # DTC rounding
        s_t = self.timing_sigma(rx_vpp, mode)
        s_tdc = math.sqrt(self.p.rx.tdc_lsb ** 2 / 6 + self.p.rx.tdc_jitter_k * dm.t_mean)
        s_dtc = math.hypot(tx.dtc_jitter_rms, tx.dtc_inl_rms)
        t_rx = t_tx + rng.normal(0, math.hypot(s_t, s_dtc), t_tx.size)
        mm = self.p.rx.tdc_gain_mismatch / 2 * np.where(np.arange(n_sym) % 2, -1, 1)
        dt = np.diff(t_rx) * (1 + mm) + rng.normal(0, s_tdc, n_sym)
        sym_hat = dmppm.intervals_to_symbols(dt, dm)
        # detection failures
        p_m, p_f = self.detection_probs(rx_vpp)
        lost = rng.random(t_tx.size) < p_m
        bad = lost[:-1] | lost[1:] | (rng.random(n_sym) < 2 * p_f)
        sym_hat = np.where(bad, rng.integers(0, dm.n_slots, n_sym), sym_hat)
        bits_hat = dmppm.symbols_to_bits(sym_hat, dm)
        return dict(ber=float(np.mean(bits_hat != bits)), ser=float(np.mean(sym_hat != sym)),
                    n_bits=bits.size)


__all__ = ["SystemModel", "LinkResult", "qfunc", "vpp_to_dbm", "dbm_to_vpp"]
