"""
Receiver analog front end (Fig. 6 / 7), sample-based at fs.

 VIN -> [C_in/R_in HPF 819 kHz] -(+noise, offset)-> S0 -> S1 ---------------------> coarse cmp
                                                         |                            | (V_th)
                                                         +-> [HPF d/dt @15 MHz] -> S2  v
                                                              -> [LPF] -> S3 (fine) <- RC one-shot
                                                                                       power gating
 mode="zero_cross": S3 fires when d/dt crosses zero (+ -> -), i.e. at the pulse PEAK,
                    independent of amplitude (the paper's technique, from LiDAR [4]).
 mode="threshold" : S3 compares the S1 output with a fixed threshold (no differentiator)
                    -> amplitude-dependent "walk" error. Kept for comparison.
"""
from __future__ import annotations
import numpy as np
from scipy import signal
from ..params import RXParams


def _crossings(x: np.ndarray, level: float, rising: bool) -> np.ndarray:
    """Fractional sample indices where x crosses level (linear interpolation)."""
    a, b = x[:-1] - level, x[1:] - level
    idx = np.nonzero((a < 0) & (b >= 0) if rising else (a > 0) & (b <= 0))[0]
    return idx + a[idx] / (a[idx] - b[idx])


class RxAFE:
    def __init__(self, p: RXParams, rng=None, mode: str = "zero_cross",
                 nominal_rx_vpp: float = 0.06):
        self.p = p
        self.mode = mode
        fs = p.fs
        rng = rng or np.random.default_rng(7)
        self.offset = rng.normal(0, p.offset_3sigma / 3)
        f_in = 1 / (2 * np.pi * p.R_in * p.C_in)
        self.sos_in = signal.butter(1, f_in, "highpass", fs=fs, output="sos")
        self.sos_amp = signal.butter(1, p.bw_amp, "lowpass", fs=fs, output="sos")
        self.sos_diff = signal.butter(1, p.f_diff, "highpass", fs=fs, output="sos")
        self.sos_lpf = signal.butter(1, p.f_lpf, "lowpass", fs=fs, output="sos")
        # threshold-mode fine threshold, designed for a nominal amplitude at S1 output
        self.vth_fine = p.threshold_mode_vth * nominal_rx_vpp * p.g_s0 * p.g_s1

    def _amp(self, x, g):
        return g * signal.sosfilt(self.sos_amp, x)

    def process(self, v_in: np.ndarray, rng, keep_waveforms: bool = False) -> dict:
        p = self.p
        fs = p.fs
        x = signal.sosfilt(self.sos_in, v_in)
        # input-referred noise of the amplifier chain, white over the simulation band
        x = x + rng.normal(0, p.en_in * np.sqrt(fs / 2), x.size) + self.offset
        s1 = self._amp(self._amp(x, p.g_s0), p.g_s1)
        d = signal.sosfilt(self.sos_diff, s1)
        s3_in = signal.sosfilt(self.sos_lpf, self._amp(d, p.g_s2))

        # ---- coarse detector + non-retriggerable RC one-shot
        trig = _crossings(s1, p.vth_coarse, rising=True) / fs
        events = []
        last = -np.inf
        for tc in trig:
            if tc >= last + p.oneshot:
                events.append(tc)
                last = tc
        events = np.array(events)

        # ---- power-gated fine comparator: active in [t_c + t_wake, t_c + oneshot]
        # threshold mode models the conventional always-on fine comparator (no wake-up delay)
        t_wake = p.t_wake if self.mode == "zero_cross" else 0.0
        n_win = int(round((p.oneshot - t_wake) * fs))
        stamps = []
        for tc in events:
            k0 = int(np.ceil((tc + t_wake) * fs))
            seg_idx = slice(k0, min(k0 + n_win, x.size))
            if self.mode == "zero_cross":
                seg = s3_in[seg_idx] + rng.normal(0, p.fine_cmp_noise, n_win)[: s3_in[seg_idx].size]
                if seg.size == 0:
                    continue
                if seg[0] <= 0:                   # woke up too late: output already high
                    stamps.append(k0 / fs)
                    continue
                c = _crossings(seg, 0.0, rising=False)
            else:
                seg = s1[seg_idx] + rng.normal(0, p.fine_cmp_noise * p.g_s2, n_win)[: s1[seg_idx].size]
                if seg.size == 0:
                    continue
                if seg[0] >= self.vth_fine:
                    stamps.append(k0 / fs)
                    continue
                c = _crossings(seg, self.vth_fine, rising=True)
            if c.size:
                stamps.append((k0 + c[0]) / fs)
        stamps = np.array(stamps)

        t_sim = v_in.size / fs
        on_time = events.size * p.oneshot if self.mode == "zero_cross" else t_sim
        power = dict(amp_s0=p.P_s0, amp_s1=p.P_s1, amp_s2=p.P_s2,
                     amp_s3=p.P_s3_on * on_time / t_sim, misc=p.P_misc)
        out = dict(timestamps=stamps, coarse_events=events, power=power,
                   s3_duty=on_time / t_sim)
        if keep_waveforms:
            gate = np.zeros(v_in.size, bool)
            for tc in events:
                k0 = int(tc * fs)
                gate[k0:k0 + int(p.oneshot * fs)] = True
            out.update(x=x, s1=s1, d=d, s3_in=s3_in, gate=gate)
        return out
