"""scripts/extract_led_positions_from_stl.py の出力が共通化（geometry.led_boards への移設）で
変わっていないことを担保する回帰テスト．

仕様出典:
- 基板ラベル: |Y| > |X| なら Y 符号で bottom/top，そうでなければ X 符号で right/left
- ID `led_<board>_<k>`，並びは bottom/top が X 昇順，right/left が Y 昇順，
  出力順は bottom → right → left → top
- 抽出は連結成分ベース（カバー = 細長い板，LED = 2.8 × 3.5 × 1 mm 程度の小板），
  発光方向は最短軸で「カバー中心 → LED 中心」の符号

移設前の ID 付与ロジック（`_legacy_assign_led_ids`）をテスト内に写して，同じ入力で同じ結果に
なることを確かめる．
"""

from __future__ import annotations

import importlib.util
import sys
from collections import defaultdict
from pathlib import Path
from types import ModuleType

import numpy as np
import pytest
import trimesh
import yaml

_ROOT = Path(__file__).resolve().parents[2]
_SCRIPT = _ROOT / "scripts" / "extract_led_positions_from_stl.py"
_BASELINE = _ROOT / "configs" / "scene_baseline.yaml"


def _load() -> ModuleType:
    name = "extract_led_positions_from_stl"
    cached = sys.modules.get(name)
    if cached is not None and Path(getattr(cached, "__file__", "")).resolve() == _SCRIPT:
        return cached
    spec = importlib.util.spec_from_file_location(name, _SCRIPT)
    assert spec is not None and spec.loader is not None
    module = importlib.util.module_from_spec(spec)
    sys.modules[name] = module
    spec.loader.exec_module(module)
    return module


def _legacy_classify(center) -> str:
    x, y = float(center[0]), float(center[1])
    if abs(y) > abs(x):
        return "bottom" if y < 0 else "top"
    return "right" if x > 0 else "left"


def _legacy_assign_led_ids(leds: list[dict], covers: list[dict]) -> list[dict]:
    """共通化前（HEAD 857b141）の _assign_led_ids の写し．"""
    cover_labels = [_legacy_classify(c["center"]) for c in covers]
    grouped: dict[str, list[dict]] = defaultdict(list)
    for led in leds:
        grouped[cover_labels[led["nearest_cover_idx"]]].append(led)
    sort_keys = {
        "bottom": lambda led: led["center"][0],
        "top": lambda led: led["center"][0],
        "right": lambda led: led["center"][1],
        "left": lambda led: led["center"][1],
    }
    result = []
    for label in ["bottom", "right", "left", "top"]:
        if label not in grouped:
            continue
        for i, led in enumerate(sorted(grouped[label], key=sort_keys[label])):
            d = dict(led)
            d["assigned_id"] = f"led_{label}_{i}"
            result.append(d)
    return result


def _synthetic_unit_mesh(include_top: bool = False) -> trimesh.Trimesh:
    """baseline の LED 18 個 + 3 枚のカバーを 1 つの STL にまとめた合成メッシュ．"""
    base = yaml.safe_load(_BASELINE.read_text(encoding="utf-8"))
    parts = []
    covers = {"bottom": ((60.0, 8.0, 2.0), (3.8, -71.0, -64.0)),
              "right": ((8.0, 60.0, 2.0), (66.0, -11.2, -64.0)),
              "left": ((8.0, 60.0, 2.0), (-66.0, -18.8, -64.0))}
    if include_top:
        covers["top"] = ((60.0, 8.0, 2.0), (0.0, 71.0, -64.0))
    for ext, c in covers.values():
        tf = np.eye(4)
        tf[:3, 3] = c
        parts.append(trimesh.creation.box(extents=ext, transform=tf))
    centers = [lt["center"] for lt in base["lights"]]
    sizes = [lt["size"] for lt in base["lights"]]
    if include_top:
        centers += [[-4.0, 71.0, -66.1], [4.0, 71.0, -66.1]]
        sizes += [[2.8, 3.5], [2.8, 3.5]]
    # 入力順を ID 順と変えておく
    rng = np.random.default_rng(0)
    for i in rng.permutation(len(centers)):
        tf = np.eye(4)
        tf[:3, 3] = centers[i]
        parts.append(trimesh.creation.box(extents=(*sizes[i], 1.05), transform=tf))
    return trimesh.util.concatenate(parts)


def test_classify_cover_position_unchanged():
    mod = _load()
    for c in [(0, -71, 0), (0, 71, 0), (66, -11, 0), (-66, -18, 0), (10, 10, 0), (-10, 10, 0),
              (0, 0, 0), (-5, -5.1, 0)]:
        assert mod._classify_cover_position(np.array(c, dtype=float)) == _legacy_classify(c)


@pytest.mark.parametrize("include_top", [False, True])
def test_assign_led_ids_matches_legacy(include_top):
    mod = _load()
    leds, covers = mod.extract_leds_from_mesh(_synthetic_unit_mesh(include_top))
    new = mod._assign_led_ids(leds, covers)
    old = _legacy_assign_led_ids(leds, covers)
    assert [d["assigned_id"] for d in new] == [d["assigned_id"] for d in old]
    for a, b in zip(new, old, strict=True):
        assert a["center"] == b["center"]
        assert a["size"] == b["size"]
        assert a["direction"] == b["direction"]


def test_extracted_yaml_entries_reproduce_baseline():
    mod = _load()
    base = yaml.safe_load(_BASELINE.read_text(encoding="utf-8"))
    leds, covers = mod.extract_leds_from_mesh(_synthetic_unit_mesh())
    entries = mod._format_led_yaml_entries(mod._assign_led_ids(leds, covers))
    assert [e["id"] for e in entries] == [lt["id"] for lt in base["lights"]]
    for e, b in zip(entries, base["lights"], strict=True):
        np.testing.assert_allclose(e["center"], b["center"], atol=1e-4)
        np.testing.assert_allclose(e["size"], b["size"], atol=1e-4)
        np.testing.assert_allclose(e["direction"], b["direction"], atol=1e-9)


def test_assign_led_ids_ties_keep_input_order():
    """同一座標の LED は入力順を保つ（sorted の安定性．移設前と同じ）．"""
    mod = _load()
    covers = [{"center": np.array([0.0, -71.0, 0.0])}]
    leds = [{"center": [1.0, -71.0, 0.0], "tag": "a", "nearest_cover_idx": 0},
            {"center": [1.0, -70.0, 0.0], "tag": "b", "nearest_cover_idx": 0},
            {"center": [0.0, -71.0, 0.0], "tag": "c", "nearest_cover_idx": 0}]
    new = mod._assign_led_ids(leds, covers)
    old = _legacy_assign_led_ids(leds, covers)
    assert [d["tag"] for d in new] == [d["tag"] for d in old] == ["c", "a", "b"]
