"""
EQS body channel: capacitive-return path loss vs distance, band-limiting, optional
multipath echo, per-pulse amplitude variation (motion, contact), 50/60 Hz mains pickup.
"""
import numpy as np
from scipy import signal
from ..params import ChannelParams


class BodyChannel:
    def __init__(self, p: ChannelParams, fs: float):
        self.p = p
        self.fs = fs
        self.sos = np.vstack([
            signal.butter(1, p.f_hp, "highpass", fs=fs, output="sos"),
            signal.butter(2, p.f_lp, "lowpass", fs=fs, output="sos"),
        ])

    def gain(self, d_cm: float) -> float:
        """Piecewise-linear interpolation in dB through the measured points (Fig. 10),
        linear extrapolation outside them."""
        d = np.array(self.p.ref_points_cm)
        g = 20 * np.log10(np.array(self.p.ref_rx_vpp) / self.p.ref_tx_vpp)
        if d_cm <= d[0]:
            gdb = g[0] + (g[1] - g[0]) / (d[1] - d[0]) * (d_cm - d[0])
        elif d_cm >= d[-1]:
            gdb = g[-1] + (g[-1] - g[-2]) / (d[-1] - d[-2]) * (d_cm - d[-1])
        else:
            gdb = np.interp(d_cm, d, g)
        return 10 ** (gdb / 20)

    def pulse_gains(self, n: int, rng) -> np.ndarray:
        return np.exp(rng.normal(0, self.p.amp_var_sigma, n))

    def propagate(self, v_tx: np.ndarray, gain: float, rng) -> np.ndarray:
        """v_tx is the electrode waveform with per-pulse variation already applied."""
        y = gain * signal.sosfilt(self.sos, v_tx)
        if self.p.echo_gain > 0:
            k = int(round(self.p.echo_delay * self.fs))
            y[k:] += self.p.echo_gain * y[:-k]
        t = np.arange(y.size) / self.fs
        y += self.p.mains_vpp / 2 * np.sin(2 * np.pi * self.p.mains_f * t + rng.uniform(0, 2 * np.pi))
        if self.p.env_noise_rms > 0:
            y += rng.normal(0, self.p.env_noise_rms, y.size)
        return y
