"""実機の白板 ROI 輝度マップ（SmTIAS-Lab の DNG から作り，output/ にキャッシュする）．

以前は `lightsim/luminance_maps/{full,bottom,left,right}_*.npy` として配っていた
マップを，Lab の DNG から同じ処理で作り直す．処理は
DNG → linear raw → LSC 順適用 → Rec.709 × 255 → portrait → 白板 ROI（`REAL_ROI`）で，
結果は shape (1409, 1400) の float32（旧 .npy と同じ）．

DNG の読み込みとデモザイクに数秒かかるため，結果を
`output/_cache/real_maps/<stem>_<処理>.npy` に保存し，DNG・meta.json より新しければ
そのまま読む．
"""

from __future__ import annotations

import logging
from pathlib import Path

import numpy as np

from sm_tias_lightsim.evaluation.dng_pipeline import dng_luminance
from sm_tias_lightsim.evaluation.roi_presets import REAL_ROI, extract_roi_xywh
from sm_tias_lightsim.lab import REPO_ROOT, V3_SHOTS, LabShot, shot_dng, shot_meta

logger = logging.getLogger(__name__)

DEFAULT_CACHE_DIR = REPO_ROOT / "output" / "_cache" / "real_maps"


def resolve_shot(shot: LabShot | str) -> LabShot:
    """撮影の指定（`LabShot` または `V3_SHOTS` のキー）を `LabShot` にする．

    Args:
        shot: `LabShot`，または `"full"`・`"bottom"`・`"left"`・`"right"`．

    Returns:
        撮影．

    Raises:
        ValueError: 知らないキーの場合．
    """
    if isinstance(shot, LabShot):
        return shot
    try:
        return V3_SHOTS[shot]
    except KeyError as exc:
        msg = f"知らない撮影の名前です: {shot!r}（使えるもの: {', '.join(V3_SHOTS)}）"
        raise ValueError(msg) from exc


def _cache_name(shot: LabShot, roi: dict, apply_lsc: bool) -> str:
    """処理条件をファイル名に入れる（条件が変われば別のキャッシュになる）．"""
    lsc = "lsc" if apply_lsc else "nolsc"
    return f"{shot.stem}_{lsc}_x{roi['x']}_y{roi['y']}_w{roi['w']}_h{roi['h']}.npy"


def real_roi_luminance(
    shot: LabShot | str,
    *,
    roi: dict | None = None,
    apply_lsc: bool = True,
    cache_dir: Path | None = DEFAULT_CACHE_DIR,
) -> np.ndarray:
    """Lab の DNG から実機の白板 ROI 輝度マップを作る（キャッシュがあれば読む）．

    Args:
        shot: 撮影（`LabShot`，または `V3_SHOTS` のキー `"full"`・`"bottom"` 等）．
        roi: 切り出す ROI（`{"x", "y", "w", "h"}`．portrait 座標）．None なら `REAL_ROI`．
        apply_lsc: True なら meta.json の lscMap を順適用する．
        cache_dir: キャッシュの置き場．None ならキャッシュを使わない．

    Returns:
        ROI の輝度マップ（h x w, float32．0〜255 の linear スケール）．

    Raises:
        FileNotFoundError: Lab・DNG・meta.json が見つからない場合．
        ValueError: 知らない撮影の名前，または DNG・meta.json の形式が不正な場合．
    """
    shot = resolve_shot(shot)
    roi = REAL_ROI if roi is None else roi
    dng = shot_dng(shot)
    meta = shot_meta(shot) if apply_lsc else None

    cache = cache_dir / _cache_name(shot, roi, apply_lsc) if cache_dir is not None else None
    if cache is not None and cache.is_file():
        sources = [dng] + ([meta] if meta is not None else [])
        if cache.stat().st_mtime >= max(p.stat().st_mtime for p in sources):
            return np.load(cache)

    luma = dng_luminance(dng, apply_lsc=apply_lsc, meta_path=meta)
    out = extract_roi_xywh(luma, roi).astype(np.float32)
    if cache is not None:
        cache.parent.mkdir(parents=True, exist_ok=True)
        np.save(cache, out)
        logger.info("実機の輝度マップをキャッシュしました: %s", cache)
    return out
