"""fusion_import.scene_gen（LED 検出・基板ラベル・光源／メッシュエントリ生成）の仕様ベーステスト．

仕様出典（Fusion 取り込みの確定事項）:
- LED 識別は OBB 寸法（回転配置にも対応）
- 発光方向の優先順: direction_overrides[オカレンス] → led.direction → 自動．判定不能は ValueError
- 基板ラベル: トップレベルオカレンスごとに既存規則．2 ユニットが同ラベルなら ValueError．
  boards で手動指定可．ID `led_<board>_<k>`，並びは bottom/top が X 昇順，right/left が Y 昇順
- 面内回転 ≥1° は警告
- 光源: ベース YAML の lights[0] をテンプレートに center/size/direction/id を差し替え
  （spot は position/direction，point は position）
- メッシュ: 対応表順 → 基板順 → manifest 順．対応表に無いボディは既定材質＋警告，id 重複は
  ValueError，exclude と LED は含めない．メッシュパスは YAML からの相対
"""

from __future__ import annotations

import logging
from pathlib import Path

import numpy as np
import pytest

from sm_tias_lightsim.fusion_import.mapping import FusionMapping, LedDetectionConfig
from sm_tias_lightsim.fusion_import.scene_gen import (
    assign_board_labels,
    build_leds,
    build_light_entries,
    build_mesh_entries,
    build_scene_dict,
    compare_lights,
    detect_led_bodies,
    generate_scene,
)
from sm_tias_lightsim.scene.schema import SceneConfig

from .conftest import rotation_from_axes, rotation_z

LED_XY = (2.8, 3.5, 1.05)
BOTTOM = "LEDユニット:1"
RIGHT = "LEDユニット:2"

AREA_TEMPLATE = {
    "id": "led_template",
    "type": "area",
    "shape": "rectangle",
    "center": [0.0, 0.0, 0.0],
    "size": [1.0, 1.0],
    "direction": [0.0, 0.0, 1.0],
    "radiance": [2807.0, 2807.0, 2807.0],
}


@pytest.fixture
def two_unit_bodies(make_body, tmp_path):
    """ルートの筐体 + 下ユニット（カバー + LED 2 個）+ 右ユニット（カバー + LED 2 個）．

    LED は manifest 上わざと並び順と逆に置く（ID 付与が座標順であることを見るため）．
    """
    mesh_dir = tmp_path / "meshes"
    return [
        make_body(0, "前側", (150, 160, 80), (0, 0, -40), stl_path=mesh_dir / "000.stl"),
        make_body(1, "LED", LED_XY, (5.0, -71.0, -66.1), BOTTOM, stl_path=mesh_dir / "001.stl"),
        make_body(2, "LED", LED_XY, (-5.0, -71.0, -66.1), BOTTOM, stl_path=mesh_dir / "002.stl"),
        make_body(3, "LED基板カバー", (60, 8, 2), (0.0, -71.0, -64.0), BOTTOM,
                  stl_path=mesh_dir / "003.stl"),
        make_body(4, "LED基板カバー", (8, 60, 2), (66.0, -10.0, -64.0), RIGHT,
                  stl_path=mesh_dir / "004.stl"),
        make_body(5, "LED", (3.5, 2.8, 1.05), (66.0, 0.0, -66.0), RIGHT,
                  stl_path=mesh_dir / "005.stl"),
        make_body(6, "LED", (3.5, 2.8, 1.05), (66.0, -20.0, -66.0), RIGHT,
                  stl_path=mesh_dir / "006.stl"),
    ]


def _mapping(**kw) -> FusionMapping:
    data = {
        "default_material": "white",
        "bodies": {
            "前側": {"id": "housing_front", "material": "white"},
            "LED基板カバー": {"id": "led_cover_{board}", "material": "white"},
        },
    }
    data.update(kw)
    return FusionMapping.model_validate(data)


# ---------------------------------------------------------------------------
# detect_led_bodies
# ---------------------------------------------------------------------------


def test_detect_led_bodies_finds_only_package_sized_boxes(two_unit_bodies):
    found = detect_led_bodies(two_unit_bodies, LedDetectionConfig())
    assert set(found) == {1, 2, 5, 6}


def test_detect_led_bodies_handles_rotated_leds(make_body):
    rot = rotation_from_axes((1.0, 2.0, 0.5), (-2.0, 1.0, 0.3))
    bodies = [
        make_body(0, "LED", LED_XY, (0, 0, 0), "U:1", rotation=rot),
        make_body(1, "LED", LED_XY, (10, 0, 0), "U:1", rotation=rotation_z(45.0)),
        # 同程度の大きさでも寸法が違えば LED ではない
        make_body(2, "ネジ", (2.0, 2.0, 2.0), (20, 0, 0), "U:1", rotation=rot),
        make_body(3, "大きい LED", (1.05, 5.0, 5.0), (30, 0, 0), "U:1"),
    ]
    assert set(detect_led_bodies(bodies, LedDetectionConfig())) == {0, 1}


def test_detect_led_bodies_uses_configured_package(make_body):
    bodies = [make_body(0, "5050", (5.0, 5.0, 1.6), (0, 0, 0), "U:1"),
              make_body(1, "2835", LED_XY, (10, 0, 0), "U:1")]
    cfg = LedDetectionConfig(package_dims_mm=(1.6, 5.0, 5.0), tolerance_mm=0.1)
    assert set(detect_led_bodies(bodies, cfg)) == {0}


# ---------------------------------------------------------------------------
# assign_board_labels
# ---------------------------------------------------------------------------


def test_board_labels_from_unit_bodies(two_unit_bodies):
    leds = detect_led_bodies(two_unit_bodies, LedDetectionConfig())
    assert assign_board_labels(two_unit_bodies, leds) == {BOTTOM: "bottom", RIGHT: "right"}


def test_duplicate_board_label_raises(make_body):
    bodies = [
        make_body(0, "LED", LED_XY, (-20.0, -71.0, -66.1), "A:1"),
        make_body(1, "カバー", (20, 8, 2), (-20.0, -71.0, -64.0), "A:1"),
        make_body(2, "LED", LED_XY, (20.0, -71.0, -66.1), "B:1"),
        make_body(3, "カバー", (20, 8, 2), (20.0, -71.0, -64.0), "B:1"),
    ]
    leds = detect_led_bodies(bodies, LedDetectionConfig())
    with pytest.raises(ValueError):
        assign_board_labels(bodies, leds)
    # boards の手動指定で解消できる
    labels = assign_board_labels(bodies, leds, {"A:1": "bottom", "B:1": "top"})
    assert labels == {"A:1": "bottom", "B:1": "top"}


def test_manual_board_label_overrides_rule(two_unit_bodies):
    leds = detect_led_bodies(two_unit_bodies, LedDetectionConfig())
    labels = assign_board_labels(two_unit_bodies, leds, {RIGHT: "left"})
    assert labels == {BOTTOM: "bottom", RIGHT: "left"}


def test_root_housing_does_not_affect_unit_label(make_body):
    """ルート直下の大きなボディ（筐体）は基板位置の判定に混ざらない．"""
    bodies = [
        make_body(0, "前側", (400, 10, 10), (190.0, 0.0, 0.0)),   # 遠く +X にある巨大な箱
        make_body(1, "LED", LED_XY, (0.0, -71.0, -66.1), BOTTOM),
        make_body(2, "カバー", (20, 8, 2), (0.0, -71.0, -64.0), BOTTOM),
    ]
    leds = detect_led_bodies(bodies, LedDetectionConfig())
    assert assign_board_labels(bodies, leds) == {BOTTOM: "bottom"}


# ---------------------------------------------------------------------------
# build_leds
# ---------------------------------------------------------------------------


def _leds(bodies, mapping=None):
    mapping = mapping or _mapping()
    boxes = detect_led_bodies(bodies, mapping.led)
    labels = assign_board_labels(bodies, boxes, mapping.boards)
    return build_leds(bodies, boxes, labels, mapping.led)


def test_led_ids_follow_board_order_and_coordinates(two_unit_bodies):
    leds = _leds(two_unit_bodies)
    assert [led.id for led in leds] == ["led_bottom_0", "led_bottom_1", "led_right_0",
                                        "led_right_1"]
    by_id = {led.id: led for led in leds}
    assert by_id["led_bottom_0"].body_index == 2   # X=-5
    assert by_id["led_bottom_1"].body_index == 1   # X=+5
    assert by_id["led_right_0"].body_index == 6    # Y=-20
    assert by_id["led_right_1"].body_index == 5    # Y=0
    assert by_id["led_right_0"].board == "right"
    assert by_id["led_right_0"].top_occurrence == RIGHT


def test_led_geometry_auto_direction_and_size(two_unit_bodies):
    by_id = {led.id: led.geometry for led in _leds(two_unit_bodies)}
    g = by_id["led_bottom_0"]
    assert g.center == pytest.approx((-5.0, -71.0, -66.1), abs=1e-9)
    assert g.direction == pytest.approx((0.0, 0.0, -1.0))
    assert g.size == pytest.approx((2.8, 3.5), abs=1e-9)
    g = by_id["led_right_0"]
    assert g.center == pytest.approx((66.0, -20.0, -66.0), abs=1e-9)
    assert g.size == pytest.approx((3.5, 2.8), abs=1e-9)


def test_direction_priority_override_then_global_then_auto(two_unit_bodies):
    mapping = _mapping(led={"direction": [1.0, 0.0, 0.0],
                            "direction_overrides": {RIGHT: [0.0, 0.0, 1.0]}})
    by_id = {led.id: led.geometry for led in _leds(two_unit_bodies, mapping)}
    assert by_id["led_bottom_0"].direction == pytest.approx((1.0, 0.0, 0.0))   # led.direction
    assert by_id["led_right_0"].direction == pytest.approx((0.0, 0.0, 1.0))    # overrides

    mapping = _mapping(led={"direction_overrides": {RIGHT: [0.0, 0.0, 1.0]}})
    by_id = {led.id: led.geometry for led in _leds(two_unit_bodies, mapping)}
    assert by_id["led_bottom_0"].direction == pytest.approx((0.0, 0.0, -1.0))  # 自動
    assert by_id["led_right_0"].direction == pytest.approx((0.0, 0.0, 1.0))


def test_unit_with_only_leds_raises_without_override(make_body):
    bodies = [make_body(0, "LED", LED_XY, (0.0, -71.0, -66.1), BOTTOM),
              make_body(1, "LED", LED_XY, (5.0, -71.0, -66.1), BOTTOM)]
    with pytest.raises(ValueError):
        _leds(bodies)
    leds = _leds(bodies, _mapping(led={"direction": [0, 0, -1]}))
    assert [led.geometry.direction for led in leds] == [(0.0, 0.0, -1.0)] * 2


def test_root_level_led_requires_explicit_direction(make_body):
    """ルート直下の LED は筐体等を参照点に使わない（ユニットの概念が無い）．"""
    bodies = [make_body(0, "前側", (150, 160, 80), (0, 0, 0)),
              make_body(1, "LED", LED_XY, (0.0, -71.0, -66.1))]
    with pytest.raises(ValueError):
        _leds(bodies)


def test_inplane_rotation_warns(make_body, caplog):
    bodies = [make_body(0, "LED", LED_XY, (0.0, -71.0, -66.1), BOTTOM, rotation=rotation_z(20)),
              make_body(1, "カバー", (20, 8, 2), (0.0, -71.0, -64.0), BOTTOM)]
    with caplog.at_level(logging.WARNING):
        leds = _leds(bodies)
    assert len(leds) == 1
    assert any(r.levelno == logging.WARNING for r in caplog.records)


def test_inplane_rotation_below_threshold_does_not_warn(make_body, caplog):
    bodies = [make_body(0, "LED", LED_XY, (0.0, -71.0, -66.1), BOTTOM, rotation=rotation_z(0.5)),
              make_body(1, "カバー", (20, 8, 2), (0.0, -71.0, -64.0), BOTTOM)]
    with caplog.at_level(logging.WARNING):
        _leds(bodies)
    assert not [r for r in caplog.records if r.levelno >= logging.WARNING]


def test_side_wall_led_gets_wall_normal_direction(make_body):
    """側壁（+X 向き）に置いた LED ユニットでも最短軸＝壁の法線方向に光る．"""
    bodies = [make_body(0, "LED", (1.05, 2.8, 3.5), (70.0, 0.0, -30.0), RIGHT),
              make_body(1, "カバー", (2, 40, 40), (68.0, 0.0, -30.0), RIGHT)]
    (led,) = _leds(bodies)
    assert led.id == "led_right_0"
    assert led.geometry.direction == pytest.approx((1.0, 0.0, 0.0))


# ---------------------------------------------------------------------------
# build_light_entries
# ---------------------------------------------------------------------------


def test_area_template_replaces_geometry_and_keeps_emission(two_unit_bodies):
    entries = build_light_entries(_leds(two_unit_bodies), AREA_TEMPLATE)
    assert [e["id"] for e in entries] == ["led_bottom_0", "led_bottom_1", "led_right_0",
                                          "led_right_1"]
    e = entries[0]
    assert e["type"] == "area"
    assert e["shape"] == "rectangle"
    assert e["radiance"] == [2807.0, 2807.0, 2807.0]
    assert e["center"] == [-5.0, -71.0, -66.1]
    assert e["size"] == [2.8, 3.5]
    assert e["direction"] == [0.0, 0.0, -1.0]
    assert entries[2]["size"] == [3.5, 2.8]
    # テンプレートは書き換えない
    assert AREA_TEMPLATE["center"] == [0.0, 0.0, 0.0]


def test_entries_are_plain_floats_without_negative_zero(two_unit_bodies):
    entries = build_light_entries(_leds(two_unit_bodies), AREA_TEMPLATE)
    for e in entries:
        for v in (*e["center"], *e["size"], *e["direction"]):
            assert type(v) is float
            if v == 0.0:
                assert np.copysign(1.0, v) > 0


def test_spot_template_uses_position_and_direction(two_unit_bodies):
    template = {"id": "s", "type": "spot", "position": [0, 0, 0], "direction": [0, 0, 1],
                "cutoff_angle": 40.0, "beam_width": 20.0, "intensity": 3.0}
    entries = build_light_entries(_leds(two_unit_bodies), template)
    e = entries[0]
    assert e["position"] == [-5.0, -71.0, -66.1]
    assert e["direction"] == [0.0, 0.0, -1.0]
    assert e["cutoff_angle"] == 40.0 and e["beam_width"] == 20.0 and e["intensity"] == 3.0
    assert "center" not in e and "size" not in e


def test_point_template_uses_position_only(two_unit_bodies):
    template = {"id": "p", "type": "point", "position": [0, 0, 0], "intensity": 1.0,
                "profile": "lambertian"}
    e = build_light_entries(_leds(two_unit_bodies), template)[0]
    assert e["position"] == [-5.0, -71.0, -66.1]
    assert e["profile"] == "lambertian"
    assert "center" not in e and "size" not in e


def test_directional_template_rejected(two_unit_bodies):
    template = {"id": "d", "type": "directional", "direction": [0, 0, -1], "irradiance": 1.0}
    with pytest.raises(ValueError):
        build_light_entries(_leds(two_unit_bodies), template)


@pytest.mark.parametrize("template", [
    AREA_TEMPLATE,
    {"id": "s", "type": "spot", "position": [0, 0, 0], "direction": [0, 0, 1],
     "cutoff_angle": 40.0, "beam_width": 20.0, "intensity": 3.0},
    {"id": "p", "type": "point", "position": [0, 0, 0], "intensity": 1.0,
     "profile": "isotropic"},
])
def test_light_entries_pass_scene_schema(two_unit_bodies, template):
    from pydantic import TypeAdapter

    from sm_tias_lightsim.scene.schema import LightConfig

    adapter = TypeAdapter(LightConfig)
    for e in build_light_entries(_leds(two_unit_bodies), template):
        adapter.validate_python(e)


# ---------------------------------------------------------------------------
# build_mesh_entries
# ---------------------------------------------------------------------------


def _meshes(bodies, mapping, yaml_dir):
    boxes = detect_led_bodies(bodies, mapping.led)
    labels = assign_board_labels(bodies, boxes, mapping.boards)
    return build_mesh_entries(bodies, set(boxes), labels, mapping, yaml_dir)


def test_mesh_entries_exclude_leds_and_expand_board(two_unit_bodies, tmp_path):
    entries = _meshes(two_unit_bodies, _mapping(), tmp_path)
    assert [e["id"] for e in entries] == ["housing_front", "led_cover_bottom", "led_cover_right"]
    assert all(e["unit"] == "mm" and e["material"] == "white" for e in entries)


def test_mesh_paths_are_relative_to_yaml_dir(two_unit_bodies, tmp_path):
    entries = _meshes(two_unit_bodies, _mapping(), tmp_path)
    for e in entries:
        assert not Path(e["path"]).is_absolute()
        assert "\\" not in e["path"]
    assert entries[0]["path"] == "meshes/000.stl"
    assert (tmp_path / entries[1]["path"]).resolve() == (tmp_path / "meshes" / "003.stl").resolve()


def test_mesh_order_follows_mapping_then_board_then_manifest(make_body, tmp_path):
    bodies = [
        make_body(0, "未登録", (10, 10, 10), (0, 0, 50)),
        make_body(1, "LED基板カバー", (8, 60, 2), (66.0, -10.0, -64.0), RIGHT),
        make_body(2, "LED", (3.5, 2.8, 1.05), (66.0, -10.0, -66.0), RIGHT),
        make_body(3, "LED基板カバー", (60, 8, 2), (0.0, -71.0, -64.0), BOTTOM),
        make_body(4, "LED", LED_XY, (0.0, -71.0, -66.1), BOTTOM),
        make_body(5, "後側", (150, 160, 10), (0, 0, 10)),
        make_body(6, "前側", (150, 160, 10), (0, 0, -90)),
    ]
    mapping = _mapping(bodies={
        "前側": {"id": "housing_front"},
        "LED基板カバー": {"id": "led_cover_{board}"},
        "後側": {"id": "housing_back"},
    })
    ids = [e["id"] for e in _meshes(bodies, mapping, tmp_path)]
    assert ids == ["housing_front", "led_cover_bottom", "led_cover_right", "housing_back",
                   "body_000"]


def test_unmapped_body_uses_default_material_with_warning(make_body, tmp_path, caplog):
    bodies = [make_body(0, "ネジ M3", (10, 10, 10), (0, 0, 50)),
              make_body(1, "LED", LED_XY, (0.0, -71.0, -66.1), BOTTOM),
              make_body(2, "LED基板カバー", (60, 8, 2), (0.0, -71.0, -64.0), BOTTOM)]
    mapping = _mapping(default_material="fallback")
    with caplog.at_level(logging.WARNING):
        entries = _meshes(bodies, mapping, tmp_path)
    unmapped = [e for e in entries if e["id"] not in ("led_cover_bottom",)]
    assert len(unmapped) == 1
    assert unmapped[0]["material"] == "fallback"
    assert unmapped[0]["id"].isascii()
    assert any(r.levelno == logging.WARNING for r in caplog.records)


def test_rule_material_defaults_to_default_material(two_unit_bodies, tmp_path):
    mapping = _mapping(default_material="grey", bodies={
        "前側": {"id": "housing_front"},
        "LED基板カバー": {"id": "led_cover_{board}", "material": "white"},
    })
    by_id = {e["id"]: e for e in _meshes(two_unit_bodies, mapping, tmp_path)}
    assert by_id["housing_front"]["material"] == "grey"
    assert by_id["led_cover_bottom"]["material"] == "white"


def test_excluded_body_is_omitted(two_unit_bodies, tmp_path):
    mapping = _mapping(bodies={"前側": {"exclude": True},
                               "LED基板カバー": {"id": "led_cover_{board}"}})
    ids = [e["id"] for e in _meshes(two_unit_bodies, mapping, tmp_path)]
    assert ids == ["led_cover_bottom", "led_cover_right"]


def test_duplicate_mesh_id_raises(two_unit_bodies, tmp_path):
    mapping = _mapping(bodies={"前側": {"id": "x"}, "LED基板カバー": {"id": "led_cover"}})
    with pytest.raises(ValueError):
        _meshes(two_unit_bodies, mapping, tmp_path)


def test_board_placeholder_outside_led_unit_raises(two_unit_bodies, tmp_path):
    mapping = _mapping(bodies={"前側": {"id": "housing_{board}"},
                               "LED基板カバー": {"id": "led_cover_{board}"}})
    with pytest.raises(ValueError):
        _meshes(two_unit_bodies, mapping, tmp_path)


# ---------------------------------------------------------------------------
# build_scene_dict / generate_scene / compare_lights
# ---------------------------------------------------------------------------


def _base_scene() -> dict:
    return {
        "name": "base",
        "description": "base desc",
        "geometry": {"meshes": [{"id": "old", "path": "old.stl", "unit": "mm",
                                 "material": "white"}]},
        "materials": {"white": {"type": "diffuse", "reflectance": 0.8}},
        "lights": [AREA_TEMPLATE],
        "sensor": {"type": "perspective", "position": [0, 0, 100], "target": [0, 0, 0],
                   "up": [0, 1, 0], "fov_deg": 40.0,
                   "film": {"width": 32, "height": 32, "rfilter": "gaussian"}},
        "render": {"variant": "scalar_rgb", "integrator": "path", "spp": 4, "max_depth": 4},
    }


def test_build_scene_dict_replaces_only_meshes_and_lights():
    base = _base_scene()
    scene = build_scene_dict(base, [{"id": "m"}], [{"id": "l"}], name="new")
    assert scene["geometry"]["meshes"] == [{"id": "m"}]
    assert scene["lights"] == [{"id": "l"}]
    assert scene["name"] == "new"
    assert scene["description"] == "base desc"
    assert scene["materials"] == base["materials"]
    assert scene["sensor"] == base["sensor"]
    assert list(scene) == list(base)
    # base は変更しない
    assert base["geometry"]["meshes"][0]["id"] == "old"
    assert base["name"] == "base"


def test_generate_scene_is_valid_scene_config(two_unit_bodies, tmp_path):
    base = _base_scene()
    SceneConfig.model_validate(base)  # テスト用ベース自体が正しいこと
    scene, leds = generate_scene(two_unit_bodies, _mapping(), base, tmp_path, name="gen")
    cfg = SceneConfig.model_validate(scene)
    assert cfg.name == "gen"
    assert [light.id for light in cfg.lights] == [led.id for led in leds]
    assert len(cfg.geometry.meshes) == 3


def test_generate_scene_without_leds_raises(make_body, tmp_path):
    bodies = [make_body(0, "前側", (150, 160, 80), (0, 0, 0))]
    with pytest.raises(ValueError):
        generate_scene(bodies, _mapping(), _base_scene(), tmp_path)


def test_generate_scene_without_base_lights_raises(two_unit_bodies, tmp_path):
    base = _base_scene()
    base["lights"] = []
    with pytest.raises(ValueError):
        generate_scene(two_unit_bodies, _mapping(), base, tmp_path)


def test_compare_lights_reports_differences():
    gen = [
        {"id": "a", "center": [0.0, 0.0, 0.0], "size": [2.8, 3.5], "direction": [0, 0, -1]},
        {"id": "b", "position": [1.0, 0.0, 0.0], "direction": [0, 0, -1]},
        {"id": "c", "center": [0.0, 0.0, 0.0]},
    ]
    ref = [
        {"id": "a", "center": [3.0, 4.0, 0.0], "size": [2.8, 3.0], "direction": [0, -1, 0]},
        {"id": "b", "position": [1.0, 0.0, 0.0], "direction": [0, 0, -1]},
        {"id": "z", "center": [0.0, 0.0, 0.0]},
    ]
    rows = {r["id"]: r for r in compare_lights(gen, ref)}
    assert [r["id"] for r in compare_lights(gen, ref)] == ["a", "b", "c", "z"]
    assert rows["a"]["status"] == "both"
    assert rows["a"]["position_diff_mm"] == pytest.approx(5.0)
    assert rows["a"]["size_diff_mm"] == pytest.approx(0.5)
    assert rows["a"]["direction_angle_deg"] == pytest.approx(90.0)
    assert rows["b"]["position_diff_mm"] == pytest.approx(0.0)
    assert rows["b"]["size_diff_mm"] is None
    assert rows["b"]["direction_angle_deg"] == pytest.approx(0.0, abs=1e-6)
    assert rows["c"]["status"] == "generated_only"
    assert rows["z"]["status"] == "reference_only"
