"""Tests for alignment transforms."""

import numpy as np
import pytest

from impakt.transform.align import XAlign, YAlign, x_align, y_align


class TestXAlign:
    def test_manual_shift(self, head_accel_x):
        shifted = x_align(head_accel_x, method="manual", reference_time=0.01)
        # Time should be shifted by -0.01s
        assert np.isclose(shifted.time[0], head_accel_x.time[0] - 0.01, atol=1e-10)

    def test_threshold_shift(self, head_accel_x):
        shifted = XAlign(
            method="threshold",
            threshold_value=5.0,
            threshold_direction="abs",
        ).apply(head_accel_x)
        # Time should be shifted so the first crossing of 5g is at t=0
        # The first crossing should be very close to t=0 in the shifted signal
        assert shifted.time[0] < 0  # Pre-trigger still negative

    def test_trigger_noop(self, head_accel_x):
        shifted = x_align(head_accel_x, method="trigger")
        assert np.array_equal(shifted.time, head_accel_x.time)


class TestYAlign:
    def test_default_baseline(self, head_accel_x):
        aligned = y_align(head_accel_x)
        # Pre-trigger region should be very close to zero
        pre_mask = aligned.time < 0
        if np.any(pre_mask):
            pre_mean = np.mean(aligned.data[pre_mask])
            assert abs(pre_mean) < 0.1  # Should be near zero

    def test_explicit_window(self, head_accel_x):
        aligned = y_align(head_accel_x, window=(-0.01, 0.0))
        # Mean over the window should be approximately zero
        mask = (aligned.time >= -0.01) & (aligned.time <= 0.0)
        window_mean = np.mean(aligned.data[mask])
        assert abs(window_mean) < 0.1

    def test_original_unchanged(self, head_accel_x):
        original = head_accel_x.data.copy()
        _ = y_align(head_accel_x)
        assert np.array_equal(head_accel_x.data, original)
