"""
(2) BLOCK-LEVEL MODELS INTEGRATED INTO A SYSTEM

bits -> DMPPM encoder -> DelayLineDTC -> ResonantTX (switched-RLC circuit) -> BodyChannel
     -> RxAFE (filters, noise, coarse detector, one-shot power gating, fine comparator)
     -> InterleavedTDC -> DMPPM decoder -> bits

Every system metric (BER, timing error, power, energy/bit, throughput) is measured from
the simulated activity of the blocks, not from formulas, so it can be checked against the
independent SystemModel.
"""
from __future__ import annotations
from copy import deepcopy
import numpy as np

from .params import SystemParams
from . import dmppm
from .blocks.dtc import DelayLineDTC
from .blocks.resonant_tx import ResonantTX
from .blocks.channel import BodyChannel
from .blocks.rx_afe import RxAFE
from .blocks.tdc import InterleavedTDC


class IntegratedSystem:
    def __init__(self, p: SystemParams | None = None, mode: str = "zero_cross",
                 calibrate_tx: bool = True, nominal_rx_vpp: float = 0.06):
        self.p = deepcopy(p) if p is not None else SystemParams()
        rng = np.random.default_rng(self.p.seed)
        self.dtc = DelayLineDTC(self.p.tx, rng=rng)
        self.tx = ResonantTX(self.p.tx)
        self.cal = self.tx.calibrate() if calibrate_tx else None
        self.pulse = self.tx.simulate_pulse()
        self.t_tmpl, self.v_tmpl = self.pulse["t"], self.pulse["v_out"]
        self.tx_vpp = float(self.v_tmpl.max())
        self.ch = BodyChannel(self.p.ch, self.p.rx.fs)
        self.rx = RxAFE(self.p.rx, rng=rng, mode=mode, nominal_rx_vpp=nominal_rx_vpp)
        self.tdc = InterleavedTDC(self.p.rx, rng=rng)

    # ------------------------------------------------------------ TX side
    def synthesize(self, t_pulses: np.ndarray, amp: np.ndarray, t_end: float) -> np.ndarray:
        """Electrode waveform: the circuit-simulated pulse placed at each DTC edge."""
        fs = self.p.rx.fs
        n = int(np.ceil(t_end * fs))
        v = np.zeros(n)
        t0, t1 = self.t_tmpl[0], self.t_tmpl[-1]
        for tk, a in zip(t_pulses, amp):
            k0 = max(int(np.floor((tk + t0) * fs)), 0)
            k1 = min(int(np.ceil((tk + t1) * fs)), n)
            tt = np.arange(k0, k1) / fs - tk
            v[k0:k1] += a * np.interp(tt, self.t_tmpl, self.v_tmpl, left=0.0, right=0.0)
        return v

    # ----------------------------------------------------------- core run
    def _simulate(self, t_ideal, pair_sym, pair_k, pulse_gain, rng, keep=False, cal=None) -> dict:
        """t_ideal: all pulse times. Symbol i is carried by pulses (pair_k[i], pair_k[i]+1).
        cal (proposal P2): preamble intervals {pre_k, pre_pkt, sym_pkt, pre_iv} for the TDC gain
        calibration; each TDC's gain per packet is the median of measured / known intervals."""
        dm, rxp = self.p.dmppm, self.p.rx
        t_tx = self.dtc.place(t_ideal, rng)
        amp = pulse_gain * self.ch.pulse_gains(t_tx.size, rng)
        t_end = t_tx[-1] + 2e-6
        v_tx = self.synthesize(t_tx, amp, t_end)
        v_rx = self.ch.propagate(v_tx, 1.0, rng)
        r = self.rx.process(v_rx, rng, keep_waveforms=keep)
        st = r["timestamps"]
        meas, which = self.tdc.measure(st, rng) if st.size > 1 else (np.array([]), np.array([]))

        # ---- decoder: intervals far beyond t_max mark a gap (missed pulse / TDMA guard)
        gap_thr = dm.t_max + 4 * dm.t_slot

        # ---- testbench alignment (truth only used for scoring, not by the receiver)
        n_sym = pair_sym.size
        tx_det = -np.ones(t_tx.size, int)
        latency = np.nan
        if st.size:
            def nearest(ts):
                j = np.clip(np.searchsorted(t_tx, ts), 1, t_tx.size - 1)
                return np.where(np.abs(ts - t_tx[j - 1]) < np.abs(ts - t_tx[j]), j - 1, j)
            latency = float(np.median(st - t_tx[nearest(st)]))
            k = nearest(st - latency)
            close = np.abs(st - latency - t_tx[k]) < dm.t_min / 2
            for si in np.nonzero(close)[0]:
                if tx_det[k[si]] < 0:
                    tx_det[k[si]] = si
        # ignore filter start-up transients before the first pulse when counting false pulses
        in_span = (st > t_tx[0] - dm.t_min / 2) & (st < t_tx[-1] + dm.t_min / 2)
        n_false = int(np.sum(in_span) - np.sum(tx_det >= 0))
        n_miss = int(np.sum(tx_det < 0))

        a, b = tx_det[pair_k], tx_det[pair_k + 1]
        ok = (a >= 0) & (b == a + 1)
        ok_idx = np.nonzero(ok)[0]
        ok[ok_idx] &= meas[a[ok_idx]] < gap_thr
        mv = meas[np.clip(a, 0, max(meas.size - 1, 0))] if meas.size else np.zeros(n_sym)
        if cal is not None:
            single = getattr(rxp, "single", False)
            groups = {}
            for k, pkt in zip(cal["pre_k"], cal["pre_pkt"]):
                ia, ib = tx_det[k], tx_det[k + 1]
                if ia < 0 or ib != ia + 1 or ia >= meas.size:
                    continue
                groups.setdefault(pkt * 2 + (0 if single else int(which[ia])), []).append(meas[ia] / cal["pre_iv"])
            est = {key: float(np.median(v)) for key, v in groups.items()}
            g = np.array([est.get(pkt * 2 + (0 if single else int(which[ai])), 1.0) if ok[i] else 1.0
                          for i, (pkt, ai) in enumerate(zip(cal["sym_pkt"], a))])
            mv = mv / g
        sym_hat = rng.integers(0, dm.n_slots, n_sym)        # lost symbols -> random guess
        sym_hat[ok] = dmppm.intervals_to_symbols(mv[ok], dm)
        bits = dmppm.symbols_to_bits(pair_sym, dm)
        bits_hat = dmppm.symbols_to_bits(sym_hat, dm)
        ideal_iv = dmppm.symbols_to_intervals(pair_sym, dm)
        t_err = mv[ok] - ideal_iv[ok]

        # ---- power, measured from block activity
        T = t_end
        n_p = t_tx.size
        e_pulse = self.pulse["energy"]
        tx_pw = dict(resistive=(e_pulse["r_series"] + e_pulse["r_tune"]) * n_p / T,
                     pass_gate=e_pulse["r_pass"] * n_p / T,
                     damper_reset=(e_pulse["damper"] + e_pulse["reset"]) * n_p / T,
                     gate=e_pulse["gate"] * n_p / T,
                     dtc=self.dtc.energy(n_p) / T,
                     leakage=self.p.tx.P_leak)
        tx_pw["supply_check"] = (e_pulse["supply"] + e_pulse["gate"]) * n_p / T  # == sum of losses
        rx_pw = dict(r["power"])
        rx_pw["tdc"] = self.tdc.energy(meas) / T
        tx_tot = sum(v for k, v in tx_pw.items() if k != "supply_check")
        rx_tot = sum(rx_pw.values())
        n_bits = bits.size
        rate = n_bits / T
        out = dict(ber=float(np.mean(bits != bits_hat)), ser=float(np.mean(sym_hat != pair_sym)),
                   n_bits=n_bits, n_miss=n_miss, n_false=n_false, latency=latency,
                   interval_err=t_err, interval_err_rms=float(np.std(t_err)) if t_err.size else np.nan,
                   bitrate=rate, tx_power=tx_tot, rx_power=rx_tot,
                   tx_breakdown=tx_pw, rx_breakdown=rx_pw,
                   tx_pj_per_bit=tx_tot / rate * 1e12, rx_pj_per_bit=rx_tot / rate * 1e12,
                   link_pj_per_bit=(tx_tot + rx_tot) / rate * 1e12,
                   s3_duty=r["s3_duty"], amp_duty=r.get("amp_duty", 1.0), which_tdc=which, sym_err_mask=sym_hat != pair_sym,
                   sym_hat=sym_hat, sym_ok=ok)
        if keep:
            out.update(t_tx=t_tx, v_tx=v_tx, v_rx=v_rx, rx=r, meas=meas)
        return out

    # ------------------------------------------------------ public runs
    def run(self, n_sym: int = 2000, rx_vpp: float | None = None, d_cm: float = 120.0,
            seed: int | None = None, keep: bool = False) -> dict:
        """Point-to-point link. rx_vpp sets the RX input amplitude directly (sensitivity
        sweeps); otherwise the channel gain for distance d_cm is used."""
        dm = self.p.dmppm
        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, t0=1e-6)
        g = (rx_vpp / self.tx_vpp) if rx_vpp is not None else self.ch.gain(d_cm)
        return self._simulate(t_ideal, sym, np.arange(n_sym), np.full(t_ideal.size, g), rng, keep)

    def run_tdma(self, nodes: list[dict], n_packets: int = 60, sym_per_packet: int = 32,
                 guard: float = 1.0e-6, seed: int | None = None, keep: bool = False) -> dict:
        """Multi-source TDMA (Fig. 10). nodes: [{'name','d_cm','rate'}]; packets are scheduled
        by weighted round-robin on the requested rates. Each packet = reference pulse + symbols."""
        dm = self.p.dmppm
        rng = np.random.default_rng(self.p.seed if seed is None else seed)
        w = np.array([n["rate"] for n in nodes], float)
        credit = np.zeros(len(nodes))
        t, times, gains, pair_k, pair_sym, pair_node = 1e-6, [], [], [], [], []
        for _ in range(n_packets):
            credit += w / w.sum()
            i = int(np.argmax(credit))
            credit[i] -= 1
            sym = rng.integers(0, dm.n_slots, sym_per_packet)
            tp = dmppm.pulse_times(sym, dm, t0=t)
            k0 = len(times)
            times.extend(tp)
            gains.extend([self.ch.gain(nodes[i]["d_cm"])] * tp.size)
            pair_k.extend(range(k0, k0 + sym_per_packet))
            pair_sym.extend(sym)
            pair_node.extend([i] * sym_per_packet)
            t = tp[-1] + guard
        pair_sym, pair_node = np.array(pair_sym), np.array(pair_node)
        r = self._simulate(np.array(times), pair_sym, np.array(pair_k), np.array(gains), rng, keep)
        per = []
        bpp = dm.bits_per_pulse
        for i, n in enumerate(nodes):
            m = pair_node == i
            per.append(dict(name=n["name"], d_cm=n["d_cm"], n_sym=int(m.sum()),
                            ser=float(np.mean(r["sym_err_mask"][m])) if m.any() else np.nan,
                            share=float(m.sum() * bpp / r["n_bits"])))
        r["nodes"] = per
        r["pair_node"] = pair_node
        return r
