"""evaluation/dng_pipeline.py の仕様ベーステスト．

仕様出典:
- docs/04_SPEC/SPEC_04_評価仕様.md（実機の DNG → linear・LSC 順適用・Rec.709・portrait）
- docs/02_ENV/ENV_04_開発コマンド.md「実機のデータ」
- dng_pipeline.py の docstring（SmTIAS-Evaluation と同じ処理．lscMap は
  (rows, cols, 4=[R, G_even, G_odd, B])，G は 2 つの平均，画像サイズへバイリニア補間）

合成の小さな meta.json で lsc_gain_rgb を検証する．実 DNG を使う dng_luminance の検証は
Lab が無ければスキップし，DNG のデコードが重いので slow を付ける．
"""

from __future__ import annotations

import json

import numpy as np
import pytest

from sm_tias_lightsim.evaluation.dng_pipeline import (
    LUMA_SCALE,
    dng_luminance,
    lsc_gain_rgb,
    meta_path_for,
)
from sm_tias_lightsim.lab import V3_SHOTS, find_lab_file


def _write_meta(path, lsc: np.ndarray, rows: int | None = None, cols: int | None = None):
    """lscMap (rows, cols, 4) を入れた meta.json を書く（ネストしたリストで，実物と同じ形）．"""
    r, c, _ = lsc.shape
    meta = {
        "lscMap": lsc.tolist(),
        "lscMapRowCount": r if rows is None else rows,
        "lscMapColumnCount": c if cols is None else cols,
    }
    path.write_text(json.dumps(meta), encoding="utf-8")
    return path


class TestLscGainRgb:
    def test_shape_and_dtype(self, tmp_path):
        lsc = np.ones((3, 4, 4))
        meta = _write_meta(tmp_path / "a.meta.json", lsc)
        gain = lsc_gain_rgb(meta, (30, 40))
        assert gain.shape == (30, 40, 3)
        assert gain.dtype == np.float64

    def test_constant_map_gives_constant_gain_per_channel(self, tmp_path):
        """R・G（G_even/G_odd の平均）・B の定数マップはそのままのゲインになる．"""
        lsc = np.zeros((3, 5, 4))
        lsc[..., 0] = 2.0  # R
        lsc[..., 1] = 1.0  # G_even
        lsc[..., 2] = 3.0  # G_odd
        lsc[..., 3] = 4.0  # B
        meta = _write_meta(tmp_path / "a.meta.json", lsc)
        gain = lsc_gain_rgb(meta, (7, 11))
        np.testing.assert_allclose(gain[..., 0], 2.0)
        np.testing.assert_allclose(gain[..., 1], 2.0)  # (1 + 3) / 2
        np.testing.assert_allclose(gain[..., 2], 4.0)

    def test_corners_match_grid_corners(self, tmp_path):
        """格子の四隅は画像の四隅に対応する（端点を合わせた補間）．"""
        rng = np.random.default_rng(0)
        lsc = rng.uniform(1.0, 3.0, size=(4, 6, 4))
        meta = _write_meta(tmp_path / "a.meta.json", lsc)
        gain = lsc_gain_rgb(meta, (20, 30))
        for gy, gx, iy, ix in [(0, 0, 0, 0), (0, -1, 0, -1), (-1, 0, -1, 0), (-1, -1, -1, -1)]:
            assert gain[iy, ix, 0] == pytest.approx(lsc[gy, gx, 0])
            assert gain[iy, ix, 1] == pytest.approx((lsc[gy, gx, 1] + lsc[gy, gx, 2]) / 2)
            assert gain[iy, ix, 2] == pytest.approx(lsc[gy, gx, 3])

    def test_linear_ramp_is_interpolated_linearly(self, tmp_path):
        """列方向に線形な格子は，画像でも列方向に線形（バイリニア補間）．"""
        cols = 5
        ramp = np.arange(cols, dtype=float)  # 0..4
        lsc = np.broadcast_to(ramp[None, :, None], (3, cols, 4)).copy()
        meta = _write_meta(tmp_path / "a.meta.json", lsc)
        w = 9  # 格子点の間に 1 点ずつ
        gain = lsc_gain_rgb(meta, (4, w))
        expected = np.linspace(0, cols - 1, w)
        for ch in range(3):
            np.testing.assert_allclose(gain[0, :, ch], expected)
            np.testing.assert_allclose(gain[-1, :, ch], expected)

    def test_row_ramp_is_interpolated_linearly(self, tmp_path):
        rows = 4
        ramp = np.arange(rows, dtype=float) * 2.0
        lsc = np.broadcast_to(ramp[:, None, None], (rows, 3, 4)).copy()
        meta = _write_meta(tmp_path / "a.meta.json", lsc)
        h = 7
        gain = lsc_gain_rgb(meta, (h, 5))
        np.testing.assert_allclose(gain[:, 2, 0], np.linspace(0, 6.0, h))

    def test_values_within_grid_range(self, tmp_path):
        rng = np.random.default_rng(1)
        lsc = rng.uniform(1.0, 4.0, size=(5, 7, 4))
        meta = _write_meta(tmp_path / "a.meta.json", lsc)
        gain = lsc_gain_rgb(meta, (50, 60))
        assert gain[..., 0].min() >= lsc[..., 0].min() - 1e-12
        assert gain[..., 0].max() <= lsc[..., 0].max() + 1e-12

    def test_rows_cols_orientation(self, tmp_path):
        """lscMapRowCount が縦，lscMapColumnCount が横（shape の (height, width) と対応）．"""
        lsc = np.zeros((2, 3, 4))
        lsc[1, :, 0] = 1.0  # 下の行だけ R=1
        meta = _write_meta(tmp_path / "a.meta.json", lsc)
        gain = lsc_gain_rgb(meta, (5, 9))
        np.testing.assert_allclose(gain[0, :, 0], 0.0)
        np.testing.assert_allclose(gain[-1, :, 0], 1.0)

    def test_missing_lsc_map_raises_value_error(self, tmp_path):
        meta = tmp_path / "a.meta.json"
        meta.write_text(json.dumps({"lscMapRowCount": 2, "lscMapColumnCount": 2}), "utf-8")
        with pytest.raises(ValueError):
            lsc_gain_rgb(meta, (4, 4))

    def test_missing_row_count_raises_value_error(self, tmp_path):
        meta = tmp_path / "a.meta.json"
        meta.write_text(json.dumps({"lscMap": [[[1, 1, 1, 1]]], "lscMapColumnCount": 1}), "utf-8")
        with pytest.raises(ValueError):
            lsc_gain_rgb(meta, (4, 4))

    def test_size_mismatch_raises_value_error(self, tmp_path):
        meta = _write_meta(tmp_path / "a.meta.json", np.ones((3, 4, 4)), rows=5, cols=4)
        with pytest.raises(ValueError):
            lsc_gain_rgb(meta, (4, 4))

    def test_non_numeric_raises_value_error(self, tmp_path):
        meta = tmp_path / "a.meta.json"
        meta.write_text(
            json.dumps({"lscMap": "abc", "lscMapRowCount": 1, "lscMapColumnCount": 1}), "utf-8"
        )
        with pytest.raises(ValueError):
            lsc_gain_rgb(meta, (4, 4))

    def test_null_row_count_raises_value_error(self, tmp_path):
        meta = tmp_path / "a.meta.json"
        meta.write_text(
            json.dumps({"lscMap": [1, 1, 1, 1], "lscMapRowCount": None, "lscMapColumnCount": 1}),
            "utf-8",
        )
        with pytest.raises(ValueError):
            lsc_gain_rgb(meta, (4, 4))


class TestMetaPathFor:
    def test_same_folder_same_stem(self, tmp_path):
        dng = tmp_path / "raw" / "SmTIAS_QM_1.dng"
        assert meta_path_for(dng) == tmp_path / "raw" / "SmTIAS_QM_1.meta.json"

    def test_accepts_str(self, tmp_path):
        assert meta_path_for(str(tmp_path / "x.dng")) == tmp_path / "x.meta.json"


def test_luma_scale_is_255():
    """0〜255 の linear スケール（Evaluation・旧 npy とそろえる）．"""
    assert LUMA_SCALE == 255.0


def test_dng_luminance_missing_meta_raises(tmp_path):
    """LSC を掛けるのに meta.json が無ければ FileNotFoundError．"""
    full = V3_SHOTS["full"]
    dng = find_lab_file(full.experiment, "raw", full.dng_name)
    if dng is None:
        pytest.skip("SmTIAS-Lab に実機の全灯 DNG がありません")
    with pytest.raises(FileNotFoundError):
        dng_luminance(dng, apply_lsc=True, meta_path=tmp_path / "missing.meta.json")


def test_dng_luminance_missing_dng_raises(tmp_path):
    with pytest.raises(FileNotFoundError):
        dng_luminance(tmp_path / "missing.dng", apply_lsc=False)


@pytest.mark.slow
class TestDngLuminanceRealDng:
    """実機の全灯 DNG で portrait・float64・LSC の掛け方を確かめる．"""

    @pytest.fixture(scope="class")
    def paths(self):
        full = V3_SHOTS["full"]
        dng = find_lab_file(full.experiment, "raw", full.dng_name)
        meta = find_lab_file(full.experiment, "raw", full.meta_name)
        if dng is None or meta is None:
            pytest.skip("SmTIAS-Lab に実機の全灯 DNG・meta.json がありません")
        return dng, meta

    @pytest.fixture(scope="class")
    def lumas(self, paths):
        dng, _ = paths
        return dng_luminance(dng, apply_lsc=True), dng_luminance(dng, apply_lsc=False)

    def test_portrait_float64(self, lumas):
        luma, _ = lumas
        assert luma.dtype == np.float64
        assert luma.ndim == 2
        assert luma.shape[0] > luma.shape[1]  # portrait

    def test_scale_0_255(self, lumas):
        _, raw = lumas
        assert raw.min() >= 0.0
        assert raw.max() <= 255.0 * 1.01

    def test_lsc_is_forward_gain(self, paths, lumas):
        """LSC 済み / 未適用 の比は，lscMap のゲインの範囲に入る（順適用）．"""
        _, meta = paths
        luma, raw = lumas
        lsc = np.asarray(json.loads(meta.read_text(encoding="utf-8"))["lscMap"], dtype=float)
        mask = raw > 10.0
        ratio = luma[mask] / raw[mask]
        assert ratio.min() >= lsc.min() * 0.99
        assert ratio.max() <= lsc.max() * 1.01
        assert luma.mean() > raw.mean()

    def test_explicit_meta_path_matches_default(self, paths, lumas):
        dng, meta = paths
        luma, _ = lumas
        np.testing.assert_array_equal(dng_luminance(dng, meta_path=meta), luma)
