r"""
Resonant TX block (Fig. 4/5): switched RLC network, solved exactly per switch state.

        V_TX --[Pass, R_on]-- LX --[L + R_esr + R_el]-- OUT --> electrode (C_load)
                               |  \--[R_damp + C_damp]--/ |
                             C_lx                         +-- C_par_out
                                                          +-- R_tune -- C_tune (7-bit bank)
                                                          +-- [Reset, R_reset] -- GND

State x = [i_L, v_lx, v_out, v_ct, v_cd]; for each switch state (pass, reset) the network is
LTI: x' = A x + B V_TX. It is discretised exactly with a matrix exponential, so the stiff
R_on * C_lx (~10 ps) time constant costs nothing.

Sequence per pulse: Pass on for one designed period (1/f_target) -> deadtime -> Reset.
"""
from __future__ import annotations
import numpy as np
from scipy.linalg import expm
from dataclasses import replace
from ..params import TXParams


class ResonantTX:
    def __init__(self, p: TXParams, dt: float = 10e-12):
        self.p = p
        self.dt = dt
        self._cache = {}

    # ----------------------------------------------------------- matrices
    def _AB(self, pass_on: bool, reset_on: bool):
        p = self.p
        Rs = p.R_esr_L + p.R_electrode
        Cm = p.C_load + p.C_par_out
        Ct = max(p.C_tune, 1e-18)
        Rt = max(p.R_tune, 1e-3)
        g_on = (1 / p.R_on_pass) if pass_on else 1e-12
        g_rs = (1 / p.R_reset) if reset_on else 1e-12
        gd = 1 / p.R_damp
        A = np.zeros((5, 5))
        B = np.zeros(5)
        # i_L:  L di/dt = v_lx - v_out - Rs i
        A[0] = [-Rs / p.L, 1 / p.L, -1 / p.L, 0, 0]
        # v_lx: C_lx dv/dt = g_on (V_TX - v_lx) - i_L - i_d,  i_d = gd (v_lx - v_out - v_cd)
        A[1] = [-1, -g_on - gd, gd, 0, gd]
        A[1] /= p.C_lx
        B[1] = g_on / p.C_lx
        # v_out: Cm dv/dt = i_L + i_d - i_t - g_rs v_out,  i_t = (v_out - v_ct)/Rt
        A[2] = [1, gd, -gd - 1 / Rt - g_rs, 1 / Rt, -gd]
        A[2] /= Cm
        # v_ct: Ct dv/dt = i_t
        A[3] = [0, 0, 1 / (Rt * Ct), -1 / (Rt * Ct), 0]
        # v_cd: Cd dv/dt = i_d
        A[4] = [0, gd, -gd, 0, -gd]
        A[4] /= p.C_damp
        if p.C_tune <= 0:     # code 0: no bank connected (as in model.js)
            A[2, 2] += 1 / (Rt * Cm)
            A[2, 3] = 0.0
            A[3] = 0.0
        return A, B

    def _step(self, pass_on: bool, reset_on: bool):
        key = (pass_on, reset_on, self.p.C_tune_code, self.p.V_TX, self.p.L, self.p.C_load)
        if key not in self._cache:
            A, B = self._AB(pass_on, reset_on)
            M = np.zeros((6, 6))
            M[:5, :5] = A
            M[:5, 5] = B * self.p.V_TX
            E = expm(M * self.dt)
            self._cache[key] = (E[:5, :5], E[:5, 5])
        return self._cache[key]

    # ------------------------------------------------------------- pulse
    def simulate_pulse(self, t_window: float = 260e-9, t_pre: float = 5e-9) -> dict:
        """One pulse from rest. Returns waveforms and an energy breakdown (J)."""
        p = self.p
        n = int(round(t_window / self.dt))
        t = np.arange(n) * self.dt - t_pre
        zcs = getattr(p, "zcs", False)
        if not zcs:
            t_off = p.t_pass
            pass_on = (t >= 0) & (t < p.t_pass)
            t_rs0 = p.t_pass + p.deadtime
            reset_on = (t >= t_rs0) & (t < t_rs0 + p.t_reset)
        else:
            # proposal P1, zero-current switching: the comparator across the pass gate is armed after
            # the first half-cycle and opens Pass when i_L returns through zero, t_zcs late
            pass_on, reset_on = np.zeros(n, bool), np.zeros(n, bool)
            Tn = 2 * np.pi * np.sqrt(p.L * (p.C_load + p.C_par_out + p.C_tune))
            t_off, t_rs0 = np.inf, p.t_pass + p.deadtime
        x = np.zeros(5)
        X = np.empty((n, 5))
        i_prev = 0.0
        for k in range(n):
            if zcs:
                if t_off == np.inf and t[k] > 0:
                    if t[k] >= 0.6 * Tn and i_prev < 0 and x[0] >= 0:
                        t_off = t[k] - self.dt * x[0] / (x[0] - i_prev) + p.t_zcs
                    elif t[k] >= 1.5 * Tn:
                        t_off = t[k]
                    if t_off != np.inf:
                        t_rs0 = t_off + p.deadtime
                i_prev = x[0]
                pass_on[k] = 0 <= t[k] < t_off
                reset_on[k] = t_rs0 <= t[k] < t_rs0 + p.t_reset
            X[k] = x
            Ad, bd = self._step(bool(pass_on[k]), bool(reset_on[k]))
            x = Ad @ x + bd
        iL, vlx, vout, vct, vcd = X.T
        Rs = p.R_esr_L + p.R_electrode
        i_sup = np.where(pass_on, (p.V_TX - vlx) / p.R_on_pass, 0.0)
        Rt = max(p.R_tune, 1e-3)
        i_t = (vout - vct) / Rt if p.C_tune > 0 else np.zeros_like(vout)
        i_d = (vlx - vout - vcd) / p.R_damp
        dt = self.dt
        E = dict(
            supply=np.sum(p.V_TX * i_sup) * dt,                 # net energy drawn from V_TX
            r_pass=np.sum(i_sup ** 2 * p.R_on_pass) * dt,
            r_series=np.sum(iL ** 2 * Rs) * dt,
            r_tune=np.sum(i_t ** 2 * Rt) * dt,
            damper=np.sum(i_d ** 2 * p.R_damp) * dt,
            reset=np.sum(np.where(reset_on, vout ** 2 / p.R_reset, 0.0)) * dt,
            gate=p.C_gate_pass * p.VDDH ** 2,
        )
        k_off = min(int(np.searchsorted(t, t_off)), n - 1)
        E["residual_at_pass_off"] = 0.5 * (p.C_load + p.C_par_out) * vout[k_off] ** 2 \
            + 0.5 * p.L * iL[k_off] ** 2
        E["total"] = E["supply"] + E["gate"]
        if zcs:
            E["zcs"] = p.E_zcs
            E["total"] += E["zcs"]
        return dict(t=t, v_out=vout, i_L=iL, v_lx=vlx, pass_on=pass_on, reset_on=reset_on,
                    i_sup=i_sup, energy=E, v_peak=float(vout.max()), k_off=k_off, t_off=float(t_off))

    def template(self, t_window: float = 260e-9) -> tuple[np.ndarray, np.ndarray]:
        """Output pulse shape (t relative to Pass rising edge, v_out)."""
        r = self.simulate_pulse(t_window)
        return r["t"], r["v_out"]

    # ------------------------------------------------------- calibration
    def calibrate(self, codes=None, metric: str = "residual") -> dict:
        """Foreground calibration (Fig. 5): sweep C_TUNE and keep the code whose tank returns
        closest to rest when Pass opens (metric='residual', |v_out| at Pass-off). Energy left in
        the tank at that instant is dumped by Reset/damper (Fig. 5's 15-30% loss).
        metric='supply' picks the least supply energy instead; that is biased toward small C
        (E ~ C^1.5), so it trades away amplitude and pulse timing."""
        codes = range(0, 2 ** self.p.C_tune_bits, 2) if codes is None else codes
        rows = []
        for c in codes:
            self.p.C_tune_code = int(c)
            self._cache.clear()
            r = self.simulate_pulse(t_window=110e-9)
            k_off = np.searchsorted(r["t"], self.p.t_pass)
            rows.append((c, r["energy"]["supply"], abs(r["v_out"][k_off]), r["v_peak"]))
        rows = np.array(rows)
        col = 1 if metric == "supply" else 2
        best = int(rows[np.argmin(rows[:, col]), 0])
        self.p.C_tune_code = best
        self._cache.clear()
        return dict(codes=rows[:, 0], supply=rows[:, 1], residual=rows[:, 2],
                    v_peak=rows[:, 3], best=best)

    def with_params(self, **kw) -> "ResonantTX":
        q = replace(self.p, **kw)
        for k, v in vars(self.p).items():     # keep attributes the proposals add (zcs, t_zcs, ...)
            if k not in vars(q):
                setattr(q, k, v)
        return ResonantTX(q, self.dt)
