"""DNG 定量モードの輝度化パイプライン（実機の輝度マップを作る）．

SmTIAS-Evaluation `src/io/dng_pipeline.py` の `dng_luminance` と同じ処理を LightSim 側に
置いたもの（Evaluation は import しない方針のため．処理を変えるときは両方をそろえる）．

- 読み込みは `load_image_dng`（output_format="rgb_float32"・linear・output_color=raw）
- DNG は RAW_SENSOR で未補正のため，meta.json の lscMap でレンズビネットを順適用（任意）
- Rec.709 で輝度化して 0〜255 の linear スケールにする（PNG の図と軸をそろえるため．
  CoV 等のスケール不変な指標は変わらない）
- センサの向き（landscape）を PNG と同じ portrait へ rot90(-1) でそろえる
"""

from __future__ import annotations

import json
from pathlib import Path

import numpy as np

from sm_tias_lightsim.evaluation.dng_loader import load_image_dng
from sm_tias_lightsim.uniformity import REC709_COEFF_B, REC709_COEFF_G, REC709_COEFF_R

# 輝度を 0〜255 のスケールで返す（Evaluation の dng_luminance・旧 luminance_maps/*.npy と同じ）
LUMA_SCALE = 255.0


def _upsample(grid: np.ndarray, shape: tuple[int, int]) -> np.ndarray:
    """(rows, cols) の格子を画像サイズ shape へバイリニア補間する．

    Args:
        grid: 補間元の格子（rows x cols）．
        shape: 補間先の画像サイズ (height, width)．

    Returns:
        補間後の配列（height x width, float64）．
    """
    rows, cols = grid.shape
    h, w = shape
    ys = np.linspace(0, rows - 1, h)
    xs = np.linspace(0, cols - 1, w)
    y0 = np.floor(ys).astype(int)
    y1 = np.minimum(y0 + 1, rows - 1)
    x0 = np.floor(xs).astype(int)
    x1 = np.minimum(x0 + 1, cols - 1)
    wy = (ys - y0)[:, None]
    wx = (xs - x0)[None, :]
    top = grid[y0][:, x0] * (1 - wx) + grid[y0][:, x1] * wx
    bot = grid[y1][:, x0] * (1 - wx) + grid[y1][:, x1] * wx
    return top * (1 - wy) + bot * wy


def lsc_gain_rgb(meta_path: Path, shape: tuple[int, int]) -> np.ndarray:
    """meta.json の lscMap を (H, W, 3) の RGB ゲインへ補間する．

    lscMap は (rows, cols, 4=[R, G_even, G_odd, B])．G は G_even と G_odd の平均を使う．

    Args:
        meta_path: meta.json のパス．
        shape: 補間先の画像サイズ (height, width)．DNG の向き（landscape）のまま渡す．

    Returns:
        RGB ゲイン（H x W x 3, float64）．

    Raises:
        ValueError: meta.json に lscMap・lscMapRowCount・lscMapColumnCount が無い，
            または要素数が合わない場合．
    """
    meta = json.loads(Path(meta_path).read_text(encoding="utf-8"))
    try:
        rows, cols = int(meta["lscMapRowCount"]), int(meta["lscMapColumnCount"])
        m = np.asarray(meta["lscMap"], dtype=np.float64).reshape(rows, cols, 4)
    except (KeyError, TypeError, ValueError) as exc:
        msg = f"meta.json の LSC マップを読めません（lscMap / lscMapRowCount 等）: {meta_path}"
        raise ValueError(msg) from exc
    return np.stack(
        [
            _upsample(m[:, :, 0], shape),
            _upsample((m[:, :, 1] + m[:, :, 2]) / 2.0, shape),
            _upsample(m[:, :, 3], shape),
        ],
        axis=2,
    )


def meta_path_for(dng_path: Path) -> Path:
    """DNG と同名の meta.json のパスを返す（`<stem>.dng` → `<stem>.meta.json`）．

    Args:
        dng_path: DNG のパス．

    Returns:
        meta.json のパス（存在は確かめない）．
    """
    dng_path = Path(dng_path)
    return dng_path.with_name(f"{dng_path.stem}.meta.json")


def dng_luminance(
    dng_path: Path, *, apply_lsc: bool = True, meta_path: Path | None = None
) -> np.ndarray:
    """DNG から portrait・linear・（任意で LSC 補正済みの）輝度画像を返す．

    Args:
        dng_path: DNG のパス．
        apply_lsc: True なら meta.json の lscMap を順適用してレンズビネットを除く．
        meta_path: meta.json のパス．None なら DNG と同名の `<stem>.meta.json`．

    Returns:
        portrait 向きの輝度画像（H x W, float64．0〜255 の linear スケール）．

    Raises:
        FileNotFoundError: DNG，または LSC に要る meta.json が無い場合．
        ValueError: DNG・meta.json の形式が不正な場合．
    """
    rgb = load_image_dng(str(dng_path), output_format="rgb_float32").astype(np.float64)
    if apply_lsc:
        meta = Path(meta_path) if meta_path is not None else meta_path_for(dng_path)
        if not meta.is_file():
            raise FileNotFoundError(f"meta.json が見つかりません（LSC 補正に必要）: {meta}")
        rgb = rgb * lsc_gain_rgb(meta, rgb.shape[:2])
    luma = (
        REC709_COEFF_R * rgb[..., 0] + REC709_COEFF_G * rgb[..., 1] + REC709_COEFF_B * rgb[..., 2]
    )
    return np.rot90(luma * LUMA_SCALE, -1)
