"""Hue による舌苔の除去のテスト（SPEC_02「(4) Hue による舌苔の除去」）.

- 舌領域は黒でない画素．背景は舌本体に入らない
- `cv2.GaussianBlur(img, (5, 5), sigmaX=0)` の後，HSV（OpenCV の値域）で白苔と黄苔を
  `cv2.inRange`（両端を含む）で取り，その和を舌苔にする
- 舌本体は舌領域から舌苔を除いたもの
- 統計量は**平滑化していない元の画像**の `cv2.cvtColor(BGR2Lab)` を L は ×100/255，a・b は −128 に
  戻して求める．L・a・b の mean・min・max・median・variance（母分散）の 15 個
- しきい値は設定で与える（最終コードとスライドの値で結果が変わる）

期待値は手計算（一様な色の画像の HSV は平滑化で変わらない）．
"""

from __future__ import annotations

import cv2
import numpy as np
import pytest

from tias_judge_model.data.coat_features import (
    NUM_TONGUE_BODY_FEATURES,
    tongue_body_feature_names,
    tongue_body_lab_statistics,
    tongue_body_mask,
)
from tias_judge_model.schema import CoatRemovalConfig

SIZE = 16
NOTHING = {"h": [179, 180], "s": [0, 0], "v": [0, 0]}  # 舌の色に当たらない範囲


def _coat(white: dict | None = None, yellow: dict | None = None) -> CoatRemovalConfig:
    return CoatRemovalConfig.model_validate(
        {"white": white or NOTHING, "yellow": yellow or NOTHING}
    )


FINAL_CODE = _coat(
    {"h": [0, 180], "s": [0, 92], "v": [0, 255]},
    {"h": [0, 89], "s": [0, 255], "v": [0, 255]},
)
SLIDE = _coat(
    {"h": [0, 180], "s": [0, 80], "v": [0, 255]},
    {"h": [0, 20], "s": [0, 255], "v": [0, 255]},
)


def _uniform(rgb: tuple[int, int, int]) -> np.ndarray:
    return np.full((SIZE, SIZE, 3), rgb, dtype=np.uint8)


def _hsv(rgb: tuple[int, int, int]) -> tuple[int, int, int]:
    pixel = np.array([[rgb[::-1]]], dtype=np.uint8)
    h, s, v = cv2.cvtColor(pixel, cv2.COLOR_BGR2HSV)[0, 0]
    return int(h), int(s), int(v)


# --- しきい値の境界（cv2.inRange は両端を含む） ---

# V=255・最小値 M の色は S = 255 − M（色相 0）．手計算の前提を cv2 でも確かめる
S_AT_92 = (255, 163, 163)
S_AT_93 = (255, 162, 162)
# R=255・B=0 で G を変えると H = 30·G/255（H は度 / 2）
H_AT_20 = (255, 170, 0)
H_AT_21 = (255, 178, 0)


def test_boundary_colors_have_the_expected_hsv() -> None:
    assert _hsv(S_AT_92) == (0, 92, 255)
    assert _hsv(S_AT_93) == (0, 93, 255)
    assert _hsv(H_AT_20) == (20, 255, 255)
    assert _hsv(H_AT_21) == (21, 255, 255)


def test_s_upper_bound_is_inclusive() -> None:
    config = _coat(white={"h": [0, 180], "s": [0, 92], "v": [0, 255]})
    assert not tongue_body_mask(_uniform(S_AT_92), config).any()  # S=92 は舌苔
    assert tongue_body_mask(_uniform(S_AT_93), config).all()  # S=93 は舌本体


def test_h_upper_bound_is_inclusive() -> None:
    config = _coat(yellow={"h": [0, 20], "s": [0, 255], "v": [0, 255]})
    assert not tongue_body_mask(_uniform(H_AT_20), config).any()
    assert tongue_body_mask(_uniform(H_AT_21), config).all()


def test_lower_bound_is_inclusive() -> None:
    config = _coat(yellow={"h": [20, 180], "s": [0, 255], "v": [0, 255]})
    assert not tongue_body_mask(_uniform(H_AT_20), config).any()
    config = _coat(yellow={"h": [21, 180], "s": [0, 255], "v": [0, 255]})
    assert tongue_body_mask(_uniform(H_AT_20), config).all()


def test_v_range_is_used() -> None:
    assert _hsv((100, 50, 50))[2] == 100
    in_range = _coat(white={"h": [0, 180], "s": [0, 255], "v": [100, 100]})
    out_of_range = _coat(white={"h": [0, 180], "s": [0, 255], "v": [101, 255]})
    assert not tongue_body_mask(_uniform((100, 50, 50)), in_range).any()
    assert tongue_body_mask(_uniform((100, 50, 50)), out_of_range).all()


def test_coat_is_the_union_of_white_and_yellow() -> None:
    # 白苔だけに当たる色も，黄苔だけに当たる色も舌苔になる
    white_only = _coat(white={"h": [0, 180], "s": [0, 92], "v": [0, 255]})
    yellow_only = _coat(yellow={"h": [0, 20], "s": [0, 255], "v": [0, 255]})
    both = _coat(
        white={"h": [0, 180], "s": [0, 92], "v": [0, 255]},
        yellow={"h": [10, 20], "s": [0, 255], "v": [0, 255]},
    )
    assert not tongue_body_mask(_uniform(S_AT_92), white_only).any()
    assert not tongue_body_mask(_uniform(H_AT_20), yellow_only).any()
    assert not tongue_body_mask(_uniform(S_AT_92), both).any()
    assert not tongue_body_mask(_uniform(H_AT_20), both).any()
    assert tongue_body_mask(_uniform((200, 30, 70)), both).all()  # 赤（H=174）はどちらでもない


# --- しきい値の設定が効く ---


def test_final_code_and_slide_thresholds_differ_on_saturation() -> None:
    # S=85 は最終コード（S 0〜92）では白苔，スライド（S 0〜80）では白苔でない
    # 色相は黄苔の範囲（スライド H 0〜20）の外にする（H=170）
    rgb = (255, 170, 212)
    h, s, _ = _hsv(rgb)
    assert s == 85
    assert 89 < h
    assert not tongue_body_mask(_uniform(rgb), FINAL_CODE).any()
    assert tongue_body_mask(_uniform(rgb), SLIDE).all()


def test_final_code_and_slide_thresholds_differ_on_hue() -> None:
    # H=60 は最終コード（H 0〜89）では黄苔，スライド（H 0〜20）では黄苔でない
    rgb = (0, 200, 0)
    h, s, _ = _hsv(rgb)
    assert h == 60
    assert s > 92
    assert not tongue_body_mask(_uniform(rgb), FINAL_CODE).any()
    assert tongue_body_mask(_uniform(rgb), SLIDE).all()


def test_final_code_yellow_range_covers_red_with_small_hue() -> None:
    # SPEC_02 の注意: 最終コードの黄苔 H 0〜89 は舌の赤の多くも含む
    rgb = (200, 40, 30)
    assert _hsv(rgb)[0] <= 5
    assert not tongue_body_mask(_uniform(rgb), FINAL_CODE).any()


# --- 背景 ---


def _half_black(rgb: tuple[int, int, int]) -> np.ndarray:
    image = _uniform(rgb)
    image[:, : SIZE // 2] = 0
    return image


def test_background_is_never_tongue_body() -> None:
    # 黒は S=0・V=0 で，どの苔の範囲にも当たらない設定でも舌本体にならない
    image = _half_black((200, 30, 70))
    body = tongue_body_mask(image, _coat())
    assert not body[:, : SIZE // 2].any()
    assert body[:, SIZE // 2 :].all()


def test_background_only_image_has_empty_body() -> None:
    assert not tongue_body_mask(np.zeros((SIZE, SIZE, 3), dtype=np.uint8), _coat()).any()


def test_dark_tongue_pixel_is_not_background() -> None:
    # どれか 1 チャンネルでも 0 でなければ舌領域（SPEC_02: 黒でない画素）
    image = np.zeros((SIZE, SIZE, 3), dtype=np.uint8)
    image[5, 5] = (1, 0, 0)
    body = tongue_body_mask(image, _coat())
    assert body[5, 5]
    assert body.sum() == 1


def test_returns_bool_mask_of_image_shape() -> None:
    body = tongue_body_mask(_half_black((200, 30, 70)), _coat())
    assert body.dtype == np.bool_
    assert body.shape == (SIZE, SIZE)


# --- 平滑化 ---


def test_coat_is_judged_after_gaussian_blur() -> None:
    # 赤い舌の中の 1 画素だけの白は，平滑化で赤に埋もれて舌苔にならない
    image = _uniform((200, 30, 70))
    image[8, 8] = (255, 255, 255)  # 平滑化しなければ S=0 で白苔
    config = _coat(white={"h": [0, 180], "s": [0, 92], "v": [0, 255]})
    assert tongue_body_mask(image, config)[8, 8]


def test_blur_matches_the_specified_call() -> None:
    # 乱数の画像で SPEC_02 の手順（RGB を BGR にしてからの GaussianBlur → HSV → inRange）と一致する
    rng = np.random.default_rng(0)
    image = rng.integers(1, 256, size=(SIZE, SIZE, 3), dtype=np.uint8)
    config = _coat(white={"h": [0, 180], "s": [0, 92], "v": [0, 255]})

    bgr = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
    blurred = cv2.GaussianBlur(bgr, (5, 5), sigmaX=0)
    hsv = cv2.cvtColor(blurred, cv2.COLOR_BGR2HSV)
    expected = ~(cv2.inRange(hsv, (0, 0, 0), (180, 92, 255)) > 0)

    np.testing.assert_array_equal(tongue_body_mask(image, config), expected)


def test_channel_order_is_rgb_input() -> None:
    # 入力は RGB．赤（RGB）の H は 0 付近で，青（RGB）の H は 120
    yellow_h20 = _coat(yellow={"h": [0, 20], "s": [0, 255], "v": [0, 255]})
    assert not tongue_body_mask(_uniform((200, 0, 0)), yellow_h20).any()
    assert tongue_body_mask(_uniform((0, 0, 200)), yellow_h20).all()


# --- Lab 統計量 ---


def _cv_lab(rgb: tuple[int, int, int]) -> np.ndarray:
    # cv2 の 8 bit の Lab を SPEC_02 の式で戻す（L ×100/255，a・b −128）．
    pixel = np.array([[rgb[::-1]]], dtype=np.uint8)
    lab = cv2.cvtColor(pixel, cv2.COLOR_BGR2Lab)[0, 0].astype(np.float64)
    return np.array([lab[0] * 100.0 / 255.0, lab[1] - 128.0, lab[2] - 128.0])


def test_feature_names_match_the_order_of_statistics() -> None:
    names = tongue_body_feature_names()
    assert NUM_TONGUE_BODY_FEATURES == 15
    assert len(names) == 15
    assert len(set(names)) == 15
    assert names[:5] == (
        "body_L_mean",
        "body_L_min",
        "body_L_max",
        "body_L_median",
        "body_L_variance",
    )
    assert names[5] == "body_a_mean"
    assert names[14] == "body_b_variance"


def test_white_converts_to_l100_a0_b0() -> None:
    stats = tongue_body_lab_statistics(_uniform((255, 255, 255)), np.ones((SIZE, SIZE), dtype=bool))
    # 8 bit の白は cv2 で (255, 128, 128) なので，戻すと (100, 0, 0)
    np.testing.assert_allclose(stats[0:4], [100.0] * 4)
    np.testing.assert_allclose(stats[5:9], [0.0] * 4)
    np.testing.assert_allclose(stats[10:14], [0.0] * 4)
    np.testing.assert_allclose(stats[[4, 9, 14]], [0.0, 0.0, 0.0])


def test_scale_of_l_and_offset_of_a_b() -> None:
    rgb = (255, 0, 0)
    raw = cv2.cvtColor(np.array([[rgb[::-1]]], dtype=np.uint8), cv2.COLOR_BGR2Lab)[0, 0]
    stats = tongue_body_lab_statistics(_uniform(rgb), np.ones((SIZE, SIZE), dtype=bool))
    assert stats[0] == pytest.approx(float(raw[0]) * 100.0 / 255.0)
    assert stats[5] == pytest.approx(float(raw[1]) - 128.0)
    assert stats[10] == pytest.approx(float(raw[2]) - 128.0)
    # 赤は a*・b* が正（−128 を忘れていないこと．cv2 の生の値のままなら 128 より大きい）
    assert 0 < stats[5] < 128
    assert 0 < stats[10] < 128


def test_statistics_order_and_population_variance() -> None:
    # 舌本体の 4 画素が 3 画素の色 A と 1 画素の色 B（中央値が A になる）
    a_rgb, b_rgb = (200, 30, 70), (120, 90, 200)
    image = np.zeros((2, 2, 3), dtype=np.uint8)
    image[0, 0] = image[0, 1] = image[1, 0] = a_rgb
    image[1, 1] = b_rgb
    a_lab, b_lab = _cv_lab(a_rgb), _cv_lab(b_rgb)

    stats = tongue_body_lab_statistics(image, np.ones((2, 2), dtype=bool)).reshape(3, 5)

    values = np.stack([a_lab, a_lab, a_lab, b_lab])
    np.testing.assert_allclose(stats[:, 0], values.mean(axis=0))
    np.testing.assert_allclose(stats[:, 1], values.min(axis=0))
    np.testing.assert_allclose(stats[:, 2], values.max(axis=0))
    np.testing.assert_allclose(stats[:, 3], a_lab)
    # 母分散（ddof=0）．1 画素の偏差で手計算: ((B − A)² × 3/16)
    np.testing.assert_allclose(stats[:, 4], (b_lab - a_lab) ** 2 * 3.0 / 16.0)


def test_statistics_use_only_the_masked_pixels() -> None:
    a_rgb, b_rgb = (200, 30, 70), (120, 90, 200)
    image = _uniform(a_rgb)
    image[0, 0] = b_rgb
    mask = np.ones((SIZE, SIZE), dtype=bool)
    mask[0, 0] = False
    stats = tongue_body_lab_statistics(image, mask).reshape(3, 5)
    np.testing.assert_allclose(stats[:, 0], _cv_lab(a_rgb))
    np.testing.assert_allclose(stats[:, 4], np.zeros(3), atol=1e-12)


def test_statistics_use_the_image_without_blur() -> None:
    # 舌本体の中の 1 画素の値が，平滑化されずにそのまま min・max に出る
    base_rgb, spot_rgb = (200, 30, 70), (150, 20, 200)
    image = _uniform(base_rgb)
    image[8, 8] = spot_rgb
    config = _coat()

    body = tongue_body_mask(image, config)
    assert body.all()
    stats = tongue_body_lab_statistics(image, body).reshape(3, 5)

    values = np.stack([_cv_lab(base_rgb), _cv_lab(spot_rgb)])
    np.testing.assert_allclose(stats[:, 1], values.min(axis=0))
    np.testing.assert_allclose(stats[:, 2], values.max(axis=0))
    np.testing.assert_allclose(stats[:, 3], _cv_lab(base_rgb))


def test_statistics_differ_from_the_rgb8_to_lab_values() -> None:
    # 色特徴量の Lab（連続値の CIE）とは別物（SPEC_02）．cv2 の 8 bit から戻した値を使う
    from tias_judge_model.data.color import rgb8_to_lab

    rgb = (200, 30, 70)
    stats = tongue_body_lab_statistics(_uniform(rgb), np.ones((SIZE, SIZE), dtype=bool))
    own = rgb8_to_lab(np.array(rgb, dtype=np.uint8))
    np.testing.assert_allclose(stats[[0, 5, 10]], _cv_lab(rgb))
    assert not np.array_equal(stats[[0, 5, 10]], own)


def test_statistics_shape_and_type() -> None:
    stats = tongue_body_lab_statistics(_uniform((200, 30, 70)), np.ones((SIZE, SIZE), dtype=bool))
    assert stats.shape == (15,)
    assert stats.dtype == np.float64
