"""fusion_import テスト共通の合成ジオメトリ（trimesh の直方体）．"""

from __future__ import annotations

from collections.abc import Callable, Sequence
from pathlib import Path

import numpy as np
import pytest
import trimesh

from sm_tias_lightsim.fusion_import.scene_gen import BodyInput


def rotation_z(deg: float) -> np.ndarray:
    """Z 軸まわりの回転（3x3）．"""
    t = np.radians(deg)
    c, s = np.cos(t), np.sin(t)
    return np.array([[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]])


def rotation_from_axes(x_axis: Sequence[float], y_axis: Sequence[float]) -> np.ndarray:
    """箱の局所 X / Y 軸が世界の x_axis / y_axis を向く回転（3x3，列が局所軸）．"""
    x = np.asarray(x_axis, dtype=float)
    y = np.asarray(y_axis, dtype=float)
    x = x / np.linalg.norm(x)
    y = y - np.dot(y, x) * x
    y = y / np.linalg.norm(y)
    return np.column_stack([x, y, np.cross(x, y)])


def box_vertices(extents: Sequence[float], center: Sequence[float],
                 rotation: np.ndarray | None = None) -> np.ndarray:
    """直方体（局所軸に沿った extents）を rotation で回し center に置いた頂点 (8, 3)．"""
    tf = np.eye(4)
    if rotation is not None:
        tf[:3, :3] = rotation
    tf[:3, 3] = center
    return np.asarray(trimesh.creation.box(extents=extents, transform=tf).vertices, dtype=float)


@pytest.fixture
def make_body() -> Callable[..., BodyInput]:
    """BodyInput を作るファクトリ．index は呼び出し側で指定する．"""

    def _make(index: int, name: str, extents: Sequence[float], center: Sequence[float],
              top_occurrence: str = "", rotation: np.ndarray | None = None,
              stl_path: Path | None = None) -> BodyInput:
        return BodyInput(
            index=index,
            name=name,
            top_occurrence=top_occurrence,
            stl_path=stl_path or Path(f"/meshes/body_{index}.stl"),
            vertices=box_vertices(extents, center, rotation),
        )

    return _make
