"""画像と正解マスクの前処理（`data/preprocess.py`）のテスト.

期待値は SPEC_02「入力の前処理」と原本（`legacy/source/main.py` の
`TongueSegDataset.__getitem__`）を基準にする．原本は import できないため，同じフォルダの
`original_tongue_seg_dataset.py` に書き写した参照実装と比べる．
ファイル I/O はすべて `tmp_path` の合成画像で行う（実データ・`legacy/` のデータは使わない）．
"""

from __future__ import annotations

import traceback
from collections.abc import Callable
from pathlib import Path

import cv2
import numpy as np
import pytest
import torch
from original_tongue_seg_dataset import original_getitem

from tongue_seg_model.data.preprocess import (
    MASK_THRESHOLD,
    image_to_tensor,
    mask_to_tensor,
    read_image,
    read_mask,
    validate_pair_size,
)

SEED = 0

# パスを出さないことを確かめるための目印（ファイル名・フォルダ名に入れる）．
MARKER_DIR = "MarkerDirQz7"
MARKER_FILE = "MarkerFileXk3"

READERS: list[Callable[[Path], np.ndarray]] = [read_image, read_mask]


def _rng() -> np.random.Generator:
    return np.random.default_rng(SEED)


def _write(path: Path, array: np.ndarray) -> Path:
    assert cv2.imwrite(str(path), array)
    return path


# ---------------------------------------------------------------------------
# image_to_tensor
# ---------------------------------------------------------------------------


def test_image_keeps_bgr_order_and_divides_by_255() -> None:
    # 1×2 の画像．画素ごとに B・G・R で値を変える（並べ替えがあれば分かる）．
    image = np.array([[[10, 20, 30], [0, 128, 255]]], dtype=np.uint8)

    tensor = image_to_tensor(image)

    assert tensor.shape == (3, 1, 2)
    assert tensor.dtype == torch.float32
    expected = torch.tensor(
        [
            [[10 / 255, 0 / 255]],  # チャンネル 0 = B
            [[20 / 255, 128 / 255]],  # チャンネル 1 = G
            [[30 / 255, 255 / 255]],  # チャンネル 2 = R
        ],
        dtype=torch.float32,
    )
    torch.testing.assert_close(tensor, expected)


def test_image_value_range_endpoints_are_exact() -> None:
    image = np.zeros((2, 2, 3), dtype=np.uint8)
    image[0, 0] = 255

    tensor = image_to_tensor(image)

    assert float(tensor.min()) == 0.0
    assert float(tensor.max()) == 1.0
    assert torch.equal(tensor[:, 0, 0], torch.ones(3))


def test_image_has_no_mean_std_normalization() -> None:
    image = _rng().integers(0, 256, size=(8, 6, 3), dtype=np.uint8)

    tensor = image_to_tensor(image)

    expected = torch.from_numpy(image.astype(np.float32) / np.float32(255.0)).permute(2, 0, 1)
    torch.testing.assert_close(tensor, expected)


@pytest.mark.parametrize(
    "array",
    [
        np.zeros((4, 4, 3), dtype=np.float32),
        np.zeros((4, 4, 3), dtype=np.uint16),
        np.zeros((4, 4), dtype=np.uint8),
        np.zeros((4, 4, 1), dtype=np.uint8),
        np.zeros((4, 4, 4), dtype=np.uint8),
    ],
    ids=["float32", "uint16", "gray-2d", "one-channel", "four-channels"],
)
def test_image_rejects_wrong_dtype_or_shape(array: np.ndarray) -> None:
    with pytest.raises(ValueError):
        image_to_tensor(array)


# ---------------------------------------------------------------------------
# mask_to_tensor
# ---------------------------------------------------------------------------


def test_mask_threshold_constant_is_128() -> None:
    assert MASK_THRESHOLD == 128


def test_mask_threshold_is_above_128() -> None:
    values = np.array([[0, 127, 128, 129, 255]], dtype=np.uint8)
    mask = np.repeat(values[:, :, None], 3, axis=2)

    tensor = mask_to_tensor(mask)

    assert tensor.shape == (2, 1, 5)
    assert tensor.dtype == torch.float32
    assert tensor[0].tolist() == [[0.0, 0.0, 0.0, 1.0, 1.0]]


def test_mask_channel1_is_inverse_of_tongue() -> None:
    mask = _rng().integers(0, 256, size=(7, 5, 3), dtype=np.uint8)

    tensor = mask_to_tensor(mask)

    assert torch.equal(tensor[1], 1.0 - tensor[0])
    assert torch.equal(tensor.sum(dim=0), torch.ones(7, 5))
    assert set(tensor.unique().tolist()) <= {0.0, 1.0}


def test_mask_uses_only_channel0() -> None:
    # チャンネル 0 だけ舌の模様．チャンネル 1・2 は逆の模様にしておく．
    tongue = np.array([[255, 0], [129, 128]], dtype=np.uint8)
    mask = np.stack([tongue, 255 - tongue, 255 - tongue], axis=2)

    tensor = mask_to_tensor(mask)

    assert tensor[0].tolist() == [[1.0, 0.0], [1.0, 0.0]]
    assert tensor[1].tolist() == [[0.0, 1.0], [0.0, 1.0]]


def test_mask_ignores_channels_1_and_2_entirely() -> None:
    rng = _rng()
    channel0 = rng.integers(0, 256, size=(6, 6), dtype=np.uint8)
    a = np.stack([channel0, *rng.integers(0, 256, size=(2, 6, 6), dtype=np.uint8)], axis=2)
    b = np.stack([channel0, *rng.integers(0, 256, size=(2, 6, 6), dtype=np.uint8)], axis=2)

    assert torch.equal(mask_to_tensor(a), mask_to_tensor(b))


@pytest.mark.parametrize(
    "array",
    [
        np.zeros((4, 4, 3), dtype=np.float32),
        np.zeros((4, 4), dtype=np.uint8),
        np.zeros((4, 4, 4), dtype=np.uint8),
    ],
    ids=["float32", "gray-2d", "four-channels"],
)
def test_mask_rejects_wrong_dtype_or_shape(array: np.ndarray) -> None:
    with pytest.raises(ValueError):
        mask_to_tensor(array)


# ---------------------------------------------------------------------------
# validate_pair_size
# ---------------------------------------------------------------------------


def test_validate_pair_size_accepts_matching_sizes() -> None:
    image = np.zeros((256, 256, 3), dtype=np.uint8)
    mask = np.zeros((256, 256, 3), dtype=np.uint8)

    validate_pair_size(image, mask, (256, 256))


def test_validate_pair_size_uses_height_width_order() -> None:
    image = np.zeros((64, 32, 3), dtype=np.uint8)
    mask = np.zeros((64, 32, 3), dtype=np.uint8)

    validate_pair_size(image, mask, (64, 32))
    with pytest.raises(ValueError):
        validate_pair_size(image, mask, (32, 64))


def test_validate_pair_size_rejects_image_mask_mismatch() -> None:
    image = np.zeros((256, 256, 3), dtype=np.uint8)
    mask = np.zeros((256, 255, 3), dtype=np.uint8)

    with pytest.raises(ValueError):
        validate_pair_size(image, mask, (256, 256))


def test_validate_pair_size_rejects_size_different_from_config() -> None:
    image = np.zeros((128, 128, 3), dtype=np.uint8)
    mask = np.zeros((128, 128, 3), dtype=np.uint8)

    with pytest.raises(ValueError):
        validate_pair_size(image, mask, (256, 256))


# ---------------------------------------------------------------------------
# read_image / read_mask（cv2.imread(..., IMREAD_COLOR) と同じ配列）
# ---------------------------------------------------------------------------


def _color_png(tmp_path: Path) -> Path:
    return _write(tmp_path / "color.png", _rng().integers(0, 256, (9, 7, 3), dtype=np.uint8))


def _color_jpeg(tmp_path: Path) -> Path:
    return _write(tmp_path / "color.jpg", _rng().integers(0, 256, (16, 12, 3), dtype=np.uint8))


def _gray_png(tmp_path: Path) -> Path:
    return _write(tmp_path / "gray.png", _rng().integers(0, 256, (9, 7), dtype=np.uint8))


def _gray_jpeg(tmp_path: Path) -> Path:
    return _write(tmp_path / "gray.jpg", _rng().integers(0, 256, (16, 12), dtype=np.uint8))


def _rgba_png(tmp_path: Path) -> Path:
    return _write(tmp_path / "rgba.png", _rng().integers(0, 256, (9, 7, 4), dtype=np.uint8))


def _png16(tmp_path: Path) -> Path:
    return _write(tmp_path / "deep.png", _rng().integers(0, 65536, (9, 7, 3), dtype=np.uint16))


@pytest.mark.parametrize("reader", READERS, ids=["read_image", "read_mask"])
@pytest.mark.parametrize(
    "make_file",
    [_color_png, _color_jpeg, _gray_png, _gray_jpeg, _rgba_png, _png16],
    ids=["color-png", "color-jpeg", "gray-png", "gray-jpeg", "rgba-png", "16bit-png"],
)
def test_read_matches_cv2_imread_color(
    tmp_path: Path,
    reader: Callable[[Path], np.ndarray],
    make_file: Callable[[Path], Path],
) -> None:
    path = make_file(tmp_path)
    expected = cv2.imread(str(path), cv2.IMREAD_COLOR)
    assert expected is not None

    actual = reader(path)

    assert actual.dtype == np.uint8
    assert actual.shape == expected.shape
    assert actual.ndim == 3 and actual.shape[2] == 3
    np.testing.assert_array_equal(actual, expected)


def test_read_image_returns_bgr_order(tmp_path: Path) -> None:
    image = np.zeros((2, 2, 3), dtype=np.uint8)
    image[..., 0] = 10  # B
    image[..., 1] = 20  # G
    image[..., 2] = 30  # R
    path = _write(tmp_path / "bgr.png", image)

    np.testing.assert_array_equal(read_image(path), image)


def test_pipeline_matches_original_getitem(tmp_path: Path) -> None:
    rng = _rng()
    image = rng.integers(0, 256, size=(32, 32, 3), dtype=np.uint8)
    # 3 チャンネルで値が違い，境界の 127・128・129 を含むマスク．
    mask = rng.integers(0, 256, size=(32, 32, 3), dtype=np.uint8)
    mask[0, :3, 0] = [127, 128, 129]
    image_path = _write(tmp_path / "sample.png", image)
    mask_path = _write(tmp_path / "label.png", mask)

    expected_sample, expected_label = original_getitem(str(image_path), str(mask_path))
    sample = image_to_tensor(read_image(image_path))
    label = mask_to_tensor(read_mask(mask_path))

    assert sample.dtype == expected_sample.dtype
    assert label.dtype == expected_label.dtype
    assert torch.equal(sample, expected_sample)
    assert torch.equal(label, expected_label)


# ---------------------------------------------------------------------------
# 読めないファイル（ValueError．パス・ファイル名を出さない）
# ---------------------------------------------------------------------------


def _marker_dir(tmp_path: Path) -> Path:
    directory = tmp_path / MARKER_DIR
    directory.mkdir()
    return directory


def _missing(tmp_path: Path) -> Path:
    return _marker_dir(tmp_path) / f"{MARKER_FILE}.png"


def _empty(tmp_path: Path) -> Path:
    path = _marker_dir(tmp_path) / f"{MARKER_FILE}.png"
    path.write_bytes(b"")
    return path


def _not_image(tmp_path: Path) -> Path:
    path = _marker_dir(tmp_path) / f"{MARKER_FILE}.png"
    path.write_bytes(b"this is not an image " * 20)
    return path


def _broken_png(tmp_path: Path) -> Path:
    ok, encoded = cv2.imencode(".png", np.zeros((8, 8, 3), dtype=np.uint8))
    assert ok
    path = _marker_dir(tmp_path) / f"{MARKER_FILE}.png"
    path.write_bytes(encoded.tobytes()[:20])
    return path


def _directory(tmp_path: Path) -> Path:
    path = _marker_dir(tmp_path) / f"{MARKER_FILE}.png"
    path.mkdir()
    return path


@pytest.mark.parametrize("reader", READERS, ids=["read_image", "read_mask"])
@pytest.mark.parametrize(
    "make_path",
    [_missing, _empty, _not_image, _broken_png, _directory],
    ids=["missing", "empty", "not-image", "truncated-png", "directory"],
)
def test_read_unreadable_file_raises_without_path(
    tmp_path: Path,
    capfd: pytest.CaptureFixture[str],
    reader: Callable[[Path], np.ndarray],
    make_path: Callable[[Path], Path],
) -> None:
    path = make_path(tmp_path)
    capfd.readouterr()  # 準備の間の出力を捨てる

    with pytest.raises(ValueError) as exc_info:
        reader(path)

    exc = exc_info.value
    formatted = "".join(traceback.format_exception(type(exc), exc, exc.__traceback__))
    captured = capfd.readouterr()
    for text in [str(exc), formatted, captured.err, captured.out]:
        assert MARKER_DIR not in text
        assert MARKER_FILE not in text
        assert str(tmp_path) not in text
