"""
Back-annotation: block-level simulation -> system-level model parameters.

0. design_coarse_gain: the paper sets the 50 mV coarse threshold so background noise causes
   < 1e-3 false positives per symbol; we size the S0/S1 gain to meet that for a given noise.
1. fit_noise_for_sensitivity: choose the RX input noise density e_n so the integrated
   block-level link reaches BER = 1e-3 at the paper's measured sensitivity (-47 dBm, 6 b/pulse).
2. fit_timing_penalty: measure the single-edge timing jitter of the real filter chain
   (HPF differentiator, amplifier poles, LPF, comparator noise) and express it as the system
   model's "differentiator SNR penalty" (the paper quotes ~3 dB).
"""
from __future__ import annotations
import math
from copy import deepcopy
import numpy as np

from .params import SystemParams, dbm_to_vpp
from .integrated import IntegratedSystem
from .system_model import SystemModel


def edge_jitter(I: IntegratedSystem, rx_vpp: float, n_sym: int = 1500, seed: int = 5) -> float:
    """RMS error of RX timestamps vs the actual TX (DTC) edges, latency removed."""
    r = I.run(n_sym, rx_vpp=rx_vpp, seed=seed, keep=True)
    st, t = r["rx"]["timestamps"], r["t_tx"]
    j = np.clip(np.searchsorted(t, st - r["latency"]), 1, t.size - 1)
    k = np.where(np.abs(st - r["latency"] - t[j - 1]) < np.abs(st - r["latency"] - t[j]), j - 1, j)
    e = st - r["latency"] - t[k]
    e = e[np.abs(e) < 10e-9]
    return float(np.std(e))


def design_coarse_gain(p: SystemParams, p_false: float = 1e-3) -> float:
    """Set g_s0 = g_s1 so the input-referred coarse threshold gives p_false per symbol
    (Rice rate, no baseline-wander credit)."""
    S = SystemModel(p, baseline_wander=False)
    _, sig_c = S.rx_noise_sigma()
    idle = p.dmppm.t_mean - p.rx.oneshot
    x = math.sqrt(2 * math.log(p.rx.bw_amp * idle / p_false))
    g = math.sqrt(p.rx.vth_coarse / (x * sig_c))
    p.rx.g_s0 = p.rx.g_s1 = g
    return g


def fit_timing_penalty(p: SystemParams, amps=(0.03, 0.05, 0.08)) -> dict:
    I = IntegratedSystem(p)
    S = SystemModel(p)
    w0 = 2 * math.pi * p.tx.f_target
    sig_fine, _ = S.rx_noise_sigma()
    meas = np.array([edge_jitter(I, a) for a in amps])
    ideal = np.array([sig_fine / (a * w0 / 2) for a in amps])      # 0 dB penalty
    pen_db = float(np.mean(20 * np.log10(meas / ideal)))
    return dict(amps=np.array(amps), measured=meas, penalty_db=pen_db)


def fit_noise_for_sensitivity(p: SystemParams, target_dbm: float = -47.0, ber: float = 1e-3,
                              en_grid=(160e-9, 190e-9, 220e-9, 250e-9, 280e-9),
                              n_sym: int = 6000) -> dict:
    v = dbm_to_vpp(target_dbm)
    bers = []
    for en in en_grid:
        q = deepcopy(p)
        q.rx.en_in = en
        design_coarse_gain(q)
        bers.append(IntegratedSystem(q).run(n_sym, rx_vpp=v, seed=17)["ber"])
    bers = np.maximum(np.array(bers), 1e-6)
    en = float(np.interp(math.log10(ber), np.log10(bers), np.array(en_grid)))
    p.rx.en_in = en
    g = design_coarse_gain(p)
    return dict(en_grid=np.array(en_grid), ber=bers, en_fit=en, g_coarse=g, target_vpp=v)


def back_annotate(p: SystemParams | None = None, verbose: bool = True) -> SystemParams:
    """Full flow: fit e_n (+ coarse gain) to the paper's sensitivity, then fit the timing
    penalty. Returns calibrated params; the penalty is stored on p as diff_penalty_db."""
    p = deepcopy(p) if p is not None else SystemParams()
    f = fit_noise_for_sensitivity(p)
    t = fit_timing_penalty(p)
    p.rx.diff_penalty_db = t["penalty_db"]
    if verbose:
        print(f"e_n = {f['en_fit'] * 1e9:.0f} nV/rtHz, S0/S1 gain = {f['g_coarse']:.2f}, "
              f"timing penalty = {t['penalty_db']:+.2f} dB")
    return p
