"""TX delay-line DTC: places each pulse edge on a 1 ns grid (paper: 1 ns resolution)."""
import numpy as np
from ..params import TXParams


class DelayLineDTC:
    """Absolute pulse times are rounded to the delay-line LSB. Each tap has a static INL
    error (fixed per chip, drawn once) and every edge picks up random jitter."""

    def __init__(self, p: TXParams, n_taps: int = 1024, rng=None):
        self.p = p
        rng = rng or np.random.default_rng(11)
        self.n_taps = n_taps
        self.inl = rng.normal(0, p.dtc_inl_rms, n_taps)

    def place(self, t_ideal: np.ndarray, rng) -> np.ndarray:
        code = np.round(t_ideal / self.p.dtc_lsb).astype(np.int64)
        t = code * self.p.dtc_lsb + self.inl[code % self.n_taps]
        return t + rng.normal(0, self.p.dtc_jitter_rms, t.size)

    def energy(self, n_pulses: int) -> float:
        return n_pulses * self.p.E_dtc_per_pulse
