"""Pruebas geométricas de tilt_lidar_transform.py con escenas sintéticas (no son mediciones de Atlas X1)."""
import math
import unittest

from tilt_lidar_transform import (TiltExtrinsics, interpolate_angle, point_in_base, rotation_about_axis,
                                  scan_to_points)


class TiltLidarTest(unittest.TestCase):
    def test_zero_tilt_is_planar(self):
        p = point_in_base(2.0, math.radians(30), 0.0, TiltExtrinsics())
        self.assertAlmostEqual(p[0], 2.0 * math.cos(math.radians(30)))
        self.assertAlmostEqual(p[1], 2.0 * math.sin(math.radians(30)))
        self.assertAlmostEqual(p[2], 0.0)

    def test_positive_tilt_points_forward_down(self):
        phi = 0.2
        x, y, z = point_in_base(1.0, 0.0, phi, TiltExtrinsics())
        self.assertAlmostEqual(x, math.cos(phi))
        self.assertAlmostEqual(y, 0.0)
        self.assertAlmostEqual(z, -math.sin(phi))

    def test_rotation_is_orthonormal(self):
        r = rotation_about_axis((0.3, 0.5, 0.8), 0.7)
        for i in range(3):
            for j in range(3):
                dot = sum(r[k][i] * r[k][j] for k in range(3))
                self.assertAlmostEqual(dot, 1.0 if i == j else 0.0)

    def test_offsets_applied(self):
        ext = TiltExtrinsics(axis_origin=(0.05, 0.0, 0.10), lidar_offset=(0.0, 0.0, 0.03))
        self.assertEqual(tuple(round(c, 12) for c in point_in_base(0.0, 0.0, 0.0, ext)), (0.05, 0.0, 0.13))

    def test_interpolation(self):
        self.assertAlmostEqual(interpolate_angle(0.5, [0.0, 1.0], [0.0, 0.2]), 0.1)
        self.assertAlmostEqual(interpolate_angle(1.0, [0.0, 1.0, 2.0], [0.0, 0.2, 0.0]), 0.2)
        with self.assertRaises(ValueError):
            interpolate_angle(1.5, [0.0, 1.0], [0.0, 0.2])
        with self.assertRaises(ValueError):
            interpolate_angle(0.5, [1.0, 0.0], [0.0, 0.2])

    def test_planar_wall_reconstruction(self):
        """Pared sintética en x = 1 m barrida durante el escaneo: todos los puntos deben quedar en x = 1."""
        n, a_min, a_inc, dt = 61, -0.3, 0.01, 0.001
        times, angles = [0.0, n * dt], [-0.3, 0.3]
        ranges = []
        for j in range(n):
            alpha = a_min + j * a_inc
            phi = interpolate_angle(j * dt, times, angles)
            ranges.append(1.0 / (math.cos(alpha) * math.cos(phi)))
        pts = scan_to_points(ranges, a_min, a_inc, 0.0, dt, times, angles, TiltExtrinsics(), 0.02, 12.0)
        self.assertEqual(len(pts), n)
        for x, _, _ in pts:
            self.assertAlmostEqual(x, 1.0, places=9)

    def test_invalid_ranges_are_dropped(self):
        pts = scan_to_points([1.0, float("inf"), float("nan"), 0.01, 20.0], 0.0, 0.1, 0.0, 0.001,
                             [0.0, 1.0], [0.0, 0.0], TiltExtrinsics(), 0.02, 12.0)
        self.assertEqual(len(pts), 1)


if __name__ == "__main__":
    unittest.main()
