import numpy as np


class GradientExporter:
    """
    Экспорт градиентных сигналов в формате test1_full/srv_interp.py
    """

    @staticmethod
    def _duplicates_delete(loc_list):
        """
        Оставляет первую встреченную точку для каждого значения времени
        (первый столбец), сохраняя исходный порядок; строка с t=0 всегда
        заменяется ведущей [0, 0].
        """
        arr = np.asarray(loc_list, dtype=float)
        seed = np.zeros((1, 2))
        if arr.size == 0:
            return seed

        times = arr[:, 0]
        _, first_idx = np.unique(times, return_index=True)
        first_idx.sort()
        keep = first_idx[times[first_idx] != 0]
        return np.vstack((seed, arr[keep]))

    @staticmethod
    def _gradient_time_convertation(params: dict, time_sample):
        g_raster_time = params["grad_raster_time"]
        return time_sample / g_raster_time

    @staticmethod
    def _gradient_ampl_convertation(params: dict, gradient_herz):
        amplitude_max = params["G_amp_max"]
        amplitude_raster = 32767
        step_hz_m = amplitude_max / amplitude_raster
        return gradient_herz / step_hz_m * 1000

    def export(self, waveforms: dict, params: dict, path: str) -> None:
        loc_t_gx = self._gradient_time_convertation(params, waveforms["t_gx"])
        loc_t_gy = self._gradient_time_convertation(params, waveforms["t_gy"])
        loc_t_gz = self._gradient_time_convertation(params, waveforms["t_gz"])

        loc_gx = self._gradient_ampl_convertation(params, waveforms["gx"])
        loc_gy = self._gradient_ampl_convertation(params, waveforms["gy"])
        loc_gz = self._gradient_ampl_convertation(params, waveforms["gz"])

        gx_out = self._duplicates_delete(np.transpose([loc_t_gx, loc_gx]))
        gy_out = self._duplicates_delete(np.transpose([loc_t_gy, loc_gy]))
        gz_out = self._duplicates_delete(np.transpose([loc_t_gz, loc_gz]))

        np.savetxt(f"{path}/gx.txt", gx_out, fmt="%10.0f")
        np.savetxt(f"{path}/gy.txt", gy_out, fmt="%10.0f")
        np.savetxt(f"{path}/gz.txt", gz_out, fmt="%10.0f")
