"""Fusion エクスポート（manifest.json + ボディごとの STL）からシーン YAML を生成する．

Fusion 側で `scripts/fusion/export_design.py` を実行して書き出したディレクトリを読み，
LED ボディを OBB 寸法で識別して lights を，それ以外のボディを対応表に従って
geometry.meshes を作る．materials・sensor・render 等はベース YAML から流用し，
光源の放射パラメータ（type・radiance・spot 設定等）はベース YAML の先頭ライトを使う．

使い方:
    uv run python scripts/fusion_to_scene.py \\
        --export-dir output/fusion_export/SmTIASv3 \\
        --base configs/scene_baseline.yaml \\
        --mapping configs/fusion/smtias_v3_mapping.yaml \\
        --out configs/_tmp_fusion/scene_smtias_v3.yaml \\
        --reference configs/scene_baseline.yaml

Fusion の STL はコンポーネントのローカル座標で出るため，manifest の transform で
ワールド座標に変換し，シーンが参照するボディの STL を `--mesh-dir`
（既定 `<--out の親>/meshes/<デザイン名>/`）に書き出す．生成 YAML はそれを相対パスで参照する．

`--reference` を付けると，生成した lights を参照 YAML の lights と id で突き合わせ，
位置・サイズ・方向の差を表示する（検証用．生成結果には影響しない）．
"""

from __future__ import annotations

import argparse
import logging
import re
import sys
from pathlib import Path

import numpy as np
import trimesh
import yaml

from sm_tias_lightsim.fusion_import.manifest import (
    FusionManifest,
    ManifestBody,
    load_manifest,
)
from sm_tias_lightsim.fusion_import.mapping import load_mapping
from sm_tias_lightsim.fusion_import.scene_gen import (
    BodyInput,
    compare_lights,
    generate_scene,
)
from sm_tias_lightsim.scene.paths import relative_mesh_path
from sm_tias_lightsim.scene.schema import SceneConfig

_logger = logging.getLogger("fusion_to_scene")


def _parse_args(argv: list[str] | None = None) -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description="Fusion エクスポート（manifest.json + STL）からシーン YAML を生成する"
    )
    parser.add_argument("--export-dir", type=Path, required=True,
                        help="export_design.py の出力ディレクトリ（manifest.json がある場所）")
    parser.add_argument("--base", type=Path, required=True,
                        help="材質・センサ・render 設定と光源テンプレートの流用元シーン YAML")
    parser.add_argument("--mapping", type=Path, required=True,
                        help="ボディ名 → メッシュ id / 材質の対応表 YAML")
    parser.add_argument("--out", type=Path, required=True, help="生成するシーン YAML のパス")
    parser.add_argument("--mesh-dir", type=Path, default=None,
                        help="ワールド座標に変換した STL の書き出し先"
                        "（既定: <--out の親>/meshes/<デザイン名>）")
    parser.add_argument("--name", default=None, help="シーン名（省略時はベース YAML の name）")
    parser.add_argument("--reference", type=Path, default=None,
                        help="lights を突き合わせる参照シーン YAML（検証用，任意）")
    parser.add_argument("--aabb-tolerance", type=float, default=0.5,
                        help="STL の外形とマニフェストの AABB の許容差 [mm]"
                        "（超えると警告，既定 0.5）")
    return parser.parse_args(argv)


def _safe_dir_name(text: str) -> str:
    """ディレクトリ名に使える文字列にする（日本語はそのまま残す）．"""
    safe = re.sub(r'[\\/:*?"<>|+\s]+', "_", text).strip("._")
    return safe or "design"


def _check_world_aabb(entry: ManifestBody, vertices: np.ndarray, stl_path: Path,
                      aabb_tolerance: float) -> None:
    """ワールド座標に変換した STL の外形をマニフェストの AABB と照合する．

    桁で食い違う（STL が cm で出た等）ときはエラー，それ以外の差は B-rep の AABB が
    緩いことがあるため警告に留める（変換の取り違えはここで大きな差として出る）．
    """
    lo, hi = vertices.min(axis=0), vertices.max(axis=0)
    ref_lo, ref_hi = np.asarray(entry.aabb_mm[0]), np.asarray(entry.aabb_mm[1])
    ref_size = float(np.max(ref_hi - ref_lo))
    stl_size = float(np.max(hi - lo))
    if ref_size > 0 and not (0.5 < stl_size / ref_size < 2.0):
        msg = (
            f"STL {stl_path} の外形（最大辺 {stl_size:.3f}）がマニフェストの AABB"
            f"（最大辺 {ref_size:.3f} mm）と桁で食い違います．STL の単位が mm で"
            "書き出されているか確認してください"
        )
        raise ValueError(msg)
    diff = float(max(np.max(np.abs(lo - ref_lo)), np.max(np.abs(hi - ref_hi))))
    if diff > aabb_tolerance:
        _logger.warning(
            "ボディ %r（%s）: ワールド変換後の STL 外形とマニフェストの AABB の差が "
            "%.3f mm あります（transform の取り違えの可能性）",
            entry.name, entry.occurrence_path or "ルート", diff,
        )


def _load_bodies(manifest: FusionManifest, export_dir: Path, mesh_dir: Path,
                 aabb_tolerance: float) -> tuple[list[BodyInput], dict[int, trimesh.Trimesh]]:
    """マニフェストの各ボディの STL を読み，ワールド座標に変換して AABB と照合する．

    Fusion の STL はコンポーネントのローカル座標で出るので，manifest の transform
    （ローカル → ワールド，平行移動 mm）を適用する．

    Returns:
        (ボディ入力のリスト，index → ワールド座標のメッシュ)．BodyInput.stl_path は
        ワールド座標の STL を書き出す予定のパス（mesh_dir 配下）．
    """
    bodies = []
    world_meshes: dict[int, trimesh.Trimesh] = {}
    for i, entry in enumerate(manifest.bodies):
        stl_path = export_dir / entry.stl
        if not stl_path.is_file():
            msg = f"マニフェストの STL が見つかりません: {stl_path}（ボディ {entry.name!r}）"
            raise FileNotFoundError(msg)
        mesh = trimesh.load_mesh(str(stl_path), force="mesh")
        if len(mesh.vertices) == 0:
            msg = f"STL に頂点がありません: {stl_path}"
            raise ValueError(msg)
        mesh.apply_transform(entry.transform_matrix())
        vertices = np.asarray(mesh.vertices, dtype=float)
        _check_world_aabb(entry, vertices, stl_path, aabb_tolerance)
        world_path = mesh_dir / Path(entry.stl).name
        bodies.append(BodyInput(index=i, name=entry.name, top_occurrence=entry.top_occurrence,
                                stl_path=world_path, vertices=vertices))
        world_meshes[i] = mesh
    return bodies, world_meshes


def _fmt_vec(v: list[float]) -> str:
    return "(" + ", ".join(f"{x:+.4f}" for x in v) + ")"


def _print_comparison(lights: list[dict], reference_path: Path) -> None:
    with reference_path.open(encoding="utf-8") as f:
        reference = yaml.safe_load(f).get("lights") or []
    rows = compare_lights(lights, reference)
    print(f"\n# lights 突き合わせ（参照: {reference_path}）")
    print(f"  {'id':<16} {'status':<15} {'pos_diff[mm]':>12} {'size_diff[mm]':>13} {'dir[deg]':>9}")

    def _num(x: float | None, fmt: str) -> str:
        return "-" if x is None else format(x, fmt)

    for r in rows:
        print(f"  {r['id']:<16} {r['status']:<15} {_num(r['position_diff_mm'], '12.4f')} "
              f"{_num(r['size_diff_mm'], '13.4f')} {_num(r['direction_angle_deg'], '9.3f')}")
    both = [r for r in rows if r["status"] == "both"]
    if both:
        pos = [r["position_diff_mm"] for r in both if r["position_diff_mm"] is not None]
        if pos:
            print(f"  一致 {len(both)} / 生成 {len(lights)} / 参照 {len(reference)}，"
                  f"位置差 max {max(pos):.4f} mm")


def main(argv: list[str] | None = None) -> int:
    logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
    args = _parse_args(argv)

    manifest_path = args.export_dir / "manifest.json"
    manifest = load_manifest(manifest_path)
    mapping = load_mapping(args.mapping)
    with args.base.open(encoding="utf-8") as f:
        base = yaml.safe_load(f)
    # ベースが壊れていると生成物も壊れるので，流用する前に検証しておく
    SceneConfig.model_validate(base)

    out_path: Path = args.out
    mesh_dir: Path = args.mesh_dir or out_path.parent / "meshes" / _safe_dir_name(manifest.design)
    bodies, world_meshes = _load_bodies(manifest, args.export_dir, mesh_dir, args.aabb_tolerance)
    print(f"# {manifest.design} (v{manifest.version}): {len(bodies)} ボディ", flush=True)

    out_path.parent.mkdir(parents=True, exist_ok=True)
    description = (
        f"Fusion 設計 {manifest.design} (v{manifest.version}) から scripts/fusion_to_scene.py で"
        f"生成．材質・センサ・render・光源の放射パラメータは {args.base.as_posix()} を流用．"
    )
    scene, leds = generate_scene(bodies, mapping, base, out_path.parent,
                                 name=args.name, description=description)
    # 生成物がスキーマで読めることを書き出し前に保証する
    SceneConfig.model_validate(scene)

    print(f"# LED {len(leds)} 個:")
    for led in leds:
        g = led.geometry
        print(f"  {led.id:<16} {led.top_occurrence:<20} center={_fmt_vec(list(g.center))} "
              f"size=({g.size[0]:.3f}, {g.size[1]:.3f}) dir={_fmt_vec(list(g.direction))}")
    print(f"# meshes {len(scene['geometry']['meshes'])} 個:")
    for m in scene["geometry"]["meshes"]:
        print(f"  {m['id']:<20} {m['material']:<16} {m['path']}")

    # シーンが参照するボディだけワールド座標の STL を書き出す（LED・除外ボディは不要）
    used_paths = {m["path"] for m in scene["geometry"]["meshes"]}
    mesh_dir.mkdir(parents=True, exist_ok=True)
    for body in bodies:
        if relative_mesh_path(body.stl_path, out_path.parent) in used_paths:
            world_meshes[body.index].export(str(body.stl_path), file_type="stl")
    print(f"# Wrote world-space STL to {mesh_dir}")

    with out_path.open("w", encoding="utf-8", newline="\n") as f:
        yaml.safe_dump(scene, f, default_flow_style=False, allow_unicode=True, sort_keys=False)
    print(f"\n# Wrote {out_path}")

    if args.reference is not None:
        _print_comparison(scene["lights"], args.reference)
    return 0


if __name__ == "__main__":
    sys.exit(main())
