"""
Two time-interleaved gated-ring-oscillator TDCs (coarse counter + fine GRO phase, 0.4 V).

Every pulse is the STOP of one interval and the START of the next, so two TDCs work in
ping-pong (Fig. 7): TDC1 measures k->k+1, TDC2 measures k+1->k+2, and so on.
Non-idealities: quantisation (random GRO start phase), accumulated GRO jitter
sigma = sqrt(k*T), and gain mismatch between the two TDCs.
"""
import numpy as np
from ..params import RXParams


class InterleavedTDC:
    def __init__(self, p: RXParams, rng=None):
        self.p = p
        rng = rng or np.random.default_rng(23)
        sc = getattr(p, "tdc_scale_err", 0.0)
        self.single = getattr(p, "single", False)    # proposal P7: one timestamp counter, no interleave mismatch
        self.gain_err = np.array([sc, sc]) if self.single else \
            np.array([+0.5, -0.5]) * p.tdc_gain_mismatch * rng.choice([-1, 1]) + sc

    def measure(self, t_edges: np.ndarray, rng) -> tuple[np.ndarray, np.ndarray]:
        """Returns (intervals, which TDC measured each one)."""
        p = self.p
        dt = np.diff(t_edges)
        which = np.zeros(dt.size, int) if self.single else np.arange(dt.size) % 2
        phase = rng.uniform(0, p.tdc_lsb, dt.size)
        q = (np.floor((dt + phase) / p.tdc_lsb) - np.floor(phase / p.tdc_lsb)) * p.tdc_lsb
        jit = rng.normal(0, 1, dt.size) * np.sqrt(p.tdc_jitter_k * np.abs(dt))
        return q * (1 + self.gain_err[which]) + jit, which

    def energy(self, intervals: np.ndarray) -> float:
        # the GRO only runs while measuring: energy ~ interval length.
        # P_tdc (15.67 uW) is quoted at 2.5 MHz conversions of ~400 ns each.
        e_per_s_running = self.p.P_tdc / (2.5e6 * 400e-9)
        return float(np.sum(np.abs(intervals)) * e_per_s_running)
