#!/usr/bin/env python3
"""Transformación de escaneos 2D de un LiDAR basculante (LD19) a puntos 3D en base_link.

Modelo (ver docs/perception/TILTING_LIDAR.md):
    p_L  = (r cos α, r sin α, 0)                           punto en lidar_link
    p_B  = o_eje + R_eje(φ(t)) · (d_L + R_L · p_L)          punto en base_link
donde o_eje es el origen del eje de basculación en base_link, R_eje(φ) la rotación alrededor del eje (por defecto +y),
d_L el desplazamiento del centro óptico del LiDAR respecto al eje (marco del soporte con φ = 0) y R_L una rotación fija
opcional del LiDAR en el soporte. φ(t) se interpola linealmente a partir de muestras medidas (no se extrapola).
Unidades: m, rad, s. Solo biblioteca estándar.
"""
from __future__ import annotations

import bisect
import math
from dataclasses import dataclass, field
from typing import Sequence

Vec = tuple[float, float, float]
Mat = tuple[Vec, Vec, Vec]
IDENTITY: Mat = ((1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0))


def rotation_about_axis(axis: Vec, angle: float) -> Mat:
    """Matriz de rotación (fórmula de Rodrigues) alrededor de un eje unitario."""
    n = math.sqrt(sum(c * c for c in axis))
    if n == 0:
        raise ValueError("El eje de rotación no puede ser nulo")
    x, y, z = (c / n for c in axis)
    c, s, t = math.cos(angle), math.sin(angle), 1.0 - math.cos(angle)
    return ((t * x * x + c, t * x * y - s * z, t * x * z + s * y),
            (t * x * y + s * z, t * y * y + c, t * y * z - s * x),
            (t * x * z - s * y, t * y * z + s * x, t * z * z + c))


def mat_vec(m: Mat, v: Vec) -> Vec:
    return tuple(m[i][0] * v[0] + m[i][1] * v[1] + m[i][2] * v[2] for i in range(3))  # type: ignore[return-value]


def add(a: Vec, b: Vec) -> Vec:
    return (a[0] + b[0], a[1] + b[1], a[2] + b[2])


@dataclass(frozen=True)
class TiltExtrinsics:
    axis_origin: Vec = (0.0, 0.0, 0.0)     # origen del eje de basculación en base_link (m)
    axis: Vec = (0.0, 1.0, 0.0)            # dirección del eje en base_link
    lidar_offset: Vec = (0.0, 0.0, 0.0)    # centro del LiDAR respecto al eje, soporte con φ = 0 (m)
    lidar_rotation: Mat = field(default=IDENTITY)  # rotación fija del LiDAR en el soporte


def interpolate_angle(t: float, times: Sequence[float], angles: Sequence[float]) -> float:
    """Ángulo medido interpolado linealmente en t. Lanza ValueError fuera del intervalo muestreado."""
    if len(times) != len(angles) or len(times) < 2:
        raise ValueError("Se necesitan al menos dos muestras (t, φ) del mismo tamaño")
    if any(b <= a for a, b in zip(times, times[1:])):
        raise ValueError("Los tiempos de las muestras deben ser estrictamente crecientes")
    if not times[0] <= t <= times[-1]:
        raise ValueError(f"t = {t:.6f} s fuera del intervalo muestreado [{times[0]:.6f}, {times[-1]:.6f}]")
    k = max(1, bisect.bisect_left(times, t))
    t0, t1 = times[k - 1], times[k]
    return angles[k - 1] + (t - t0) / (t1 - t0) * (angles[k] - angles[k - 1])


def point_in_base(r: float, alpha: float, phi: float, ext: TiltExtrinsics) -> Vec:
    p_l = (r * math.cos(alpha), r * math.sin(alpha), 0.0)
    p_mount = add(ext.lidar_offset, mat_vec(ext.lidar_rotation, p_l))
    return add(ext.axis_origin, mat_vec(rotation_about_axis(ext.axis, phi), p_mount))


def scan_to_points(ranges: Sequence[float], angle_min: float, angle_increment: float, t_scan: float,
                   time_increment: float, sample_times: Sequence[float], sample_angles: Sequence[float],
                   ext: TiltExtrinsics, range_min: float, range_max: float) -> list[Vec]:
    """Convierte un escaneo en puntos 3D de base_link usando el ángulo real interpolado de cada punto.

    Se descartan rangos no finitos o fuera de [range_min, range_max].
    """
    points: list[Vec] = []
    for j, r in enumerate(ranges):
        if not math.isfinite(r) or not range_min <= r <= range_max:
            continue
        t_j = t_scan + j * time_increment
        phi = interpolate_angle(t_j, sample_times, sample_angles)
        points.append(point_in_base(r, angle_min + j * angle_increment, phi, ext))
    return points
