"""YAML 材料定義 → Mitsuba BSDF dict 変換モジュール．"""

from __future__ import annotations

from sm_tias_lightsim.scene.schema import (
    BlendBSDFConfig,
    DielectricMaterial,
    DiffuseMaterial,
    MaterialConfig,
    RoughConductorBSDFConfig,
    ThinDielectricMaterial,
)


def _to_rgb(value: float | tuple[float, float, float]) -> list[float]:
    """スカラまたは RGB タプルを 3 要素の float リストに正規化する．

    lights.py / materials.py 共通のヘルパ．このモジュールが正本で，
    lights.py はここから import して重複を回避する．

    Args:
        value: スカラ（全チャンネル同値）または RGB タプル．

    Returns:
        3 要素の float リスト．
    """
    if isinstance(value, (int, float)):
        return [float(value)] * 3
    return list(value)


def _build_bsdf_dict(material: object) -> dict:
    """1 つの BSDF config を Mitsuba BSDF dict に再帰変換する（内部ヘルパ）．

    BlendBSDFConfig の components は再帰的に変換する．

    Args:
        material: DiffuseMaterial / DielectricMaterial / ThinDielectricMaterial /
                  RoughConductorBSDFConfig / BlendBSDFConfig のいずれか．

    Returns:
        Mitsuba BSDF dict．

    Raises:
        ValueError: 未対応の材料タイプが指定された場合．
    """
    if isinstance(material, DiffuseMaterial):
        return {
            "type": "diffuse",
            "reflectance": {
                "type": "rgb",
                "value": _to_rgb(material.reflectance),
            },
        }

    if isinstance(material, DielectricMaterial):
        return {
            "type": "dielectric",
            "int_ior": material.int_ior,
            "ext_ior": material.ext_ior,
        }

    if isinstance(material, ThinDielectricMaterial):
        return {
            "type": "thindielectric",
            "int_ior": material.int_ior,
            "ext_ior": material.ext_ior,
        }

    if isinstance(material, RoughConductorBSDFConfig):
        # material="none" で eta/k なし（完全反射体）として扱う
        return {
            "type": "roughconductor",
            "alpha": material.alpha,
            "distribution": material.distribution,
            "material": "none",
        }

    if isinstance(material, BlendBSDFConfig):
        # components は必ず 2 要素（スキーマで min_length=2, max_length=2 を保証）
        return {
            "type": "blendbsdf",
            "weight": material.weight,
            "bsdf_0": _build_bsdf_dict(material.components[0]),
            "bsdf_1": _build_bsdf_dict(material.components[1]),
        }

    msg = f"Unsupported material type: {type(material).__name__}"
    raise ValueError(msg)


def build_material_dict(material: MaterialConfig) -> dict:
    """1 MaterialConfig を Mitsuba BSDF dict に変換する．

    Args:
        material: SceneConfig.materials の値（DiffuseMaterial / BlendBSDFConfig 等）．

    Returns:
        Mitsuba BSDF dict．
        - diffuse → {"type": "diffuse", "reflectance": {"type":"rgb","value":[r,g,b]}}
        - dielectric → {"type": "dielectric", "int_ior": ..., "ext_ior": ...}
        - thindielectric → {"type": "thindielectric", "int_ior": ..., "ext_ior": ...}
        - roughconductor → {"type": "roughconductor", "alpha": ..., "distribution": ...,
          "material": "none"}
        - blendbsdf → {"type": "blendbsdf", "weight": ..., "bsdf_0": ..., "bsdf_1": ...}

    Raises:
        ValueError: 未対応の材料タイプが指定された場合．
    """
    return _build_bsdf_dict(material)
