"""DeepTIAS の特徴量の読み込みのテスト（SPEC_02「(2) SVM（苔の除去なし）」）.

- 版 3 の manifest の所見 `deeptias_features` の `exChiu-lateral-{L,a,b}-{min,median,mean,max,
  variance}` の 15 列を，行の順・列の順に `(N, 15)` にする
- 列が欠けた・空の・数値でない・有限でない行があれば，件数と最初の行番号で止める（値は出さない）
- `data.root` の設定では使えない
- 例外に患者 ID・ハッシュ・パスを出さない

バンドルは tmp に作る合成のもの（`tiasdata` 自身の関数で組み立てる）．
"""

from __future__ import annotations

import hashlib
from pathlib import Path

import numpy as np
import pytest
from tiasdata.bundle import BUNDLE_FORMAT, BundleInfo, build_dataset_json, build_sha256sums
from tiasdata.manifest import ManifestEntry, build_manifest, manifest_sha256

from tias_judge_model.data.bundle import (
    DEEPTIAS_LATERAL_FEATURE_NAMES,
    DatasetSource,
    deeptias_feature_matrix,
    load_dataset_source,
)
from tias_judge_model.data.manifest import ManifestRecord
from tias_judge_model.schema import DataConfig

SECRET = "SECRETSUBJ"
SHA = "a" * 64
NAMES = DEEPTIAS_LATERAL_FEATURE_NAMES
LINE_OF_FIRST_ROW = 2  # manifest.csv の 1 行目は見出し


def _record(i: int = 0) -> ManifestRecord:
    return ManifestRecord(
        image_path=f"{SHA[:-4]}{i:04d}.png",
        patient_id=f"{SECRET}{i}",
        label="red",
        severity="strong",
    )


def _good_values(offset: float = 0.0) -> dict[str, str | None]:
    return {name: str(offset + j) for j, name in enumerate(NAMES)}


def _source(rows: list[dict[str, str | None] | None], fingerprint=None) -> DatasetSource:
    annotations = tuple(
        {"tongue_color": {"label": "red", "severity": "strong"}}
        | ({} if values is None else {"deeptias_features": values})
        for values in rows
    )
    return DatasetSource(
        records=[_record(i) for i in range(len(rows))],
        images_dir=Path("unused"),
        fingerprint=fingerprint,
        annotations=annotations,
    )


def _assert_no_identifiers(message: str) -> None:
    assert SECRET not in message
    assert SHA[:12] not in message
    assert ".png" not in message
    assert "unused" not in message  # images_dir のパス


def test_feature_names_are_the_fifteen_lateral_columns() -> None:
    assert len(NAMES) == 15
    assert len(set(NAMES)) == 15
    for channel in ("L", "a", "b"):
        for stat in ("min", "median", "mean", "max", "variance"):
            assert f"exChiu-lateral-{channel}-{stat}" in NAMES


def test_matrix_follows_row_and_column_order() -> None:
    matrix = deeptias_feature_matrix(_source([_good_values(0.0), _good_values(100.0)]))
    assert matrix.shape == (2, 15)
    assert matrix.dtype == np.float64
    np.testing.assert_array_equal(matrix[0], np.arange(15, dtype=np.float64))
    np.testing.assert_array_equal(matrix[1], 100.0 + np.arange(15, dtype=np.float64))


def test_matrix_keeps_negative_and_exponent_values() -> None:
    values = _good_values()
    values[NAMES[0]] = "-3.25"
    values[NAMES[1]] = "1.5e2"
    matrix = deeptias_feature_matrix(_source([values]))
    assert matrix[0, 0] == -3.25
    assert matrix[0, 1] == 150.0


@pytest.mark.parametrize(
    ("cell", "expected"),
    [
        ("1", 1.0),
        ("0", 0.0),
        ("-0", 0.0),
        ("-1.5", -1.5),
        ("1e-3", 1e-3),
        ("1.5E+2", 150.0),
        ("1E5", 1e5),
        ("-3.25e-07", -3.25e-07),
        ("1e+16", 1e16),
        ("+1", 1.0),
        ("1.", 1.0),
        (".5", 0.5),
    ],
)
def test_ascii_number_notations_are_accepted(cell: str, expected: float) -> None:
    values = _good_values()
    values[NAMES[3]] = cell
    assert deeptias_feature_matrix(_source([values]))[0, 3] == expected


@pytest.mark.parametrize(
    "cell",
    [
        pytest.param("1_000", id="underscore"),
        pytest.param(" 1.0 ", id="spaces_around"),
        pytest.param("1.0\n", id="trailing_newline"),
        pytest.param("\t1", id="leading_tab"),
        pytest.param("\uff11\uff12", id="fullwidth_digits"),
        pytest.param("\u0661", id="arabic_indic_digit"),
        pytest.param("1\u00a0", id="trailing_nbsp"),
        pytest.param("0x10", id="hex"),
        pytest.param("1e", id="exponent_without_digits"),
        pytest.param(".", id="dot_only"),
        pytest.param("nan", id="nan"),
        pytest.param("inf", id="inf"),
        pytest.param("1e999", id="overflow"),
    ],
)
def test_other_notations_stop_with_count_line_and_column_only(cell: str) -> None:
    values = _good_values()
    values[NAMES[3]] = cell
    with pytest.raises(ValueError) as excinfo:
        deeptias_feature_matrix(_source([values]))
    message = str(excinfo.value)
    assert "1 件" in message
    assert f"{LINE_OF_FIRST_ROW} 行目" in message
    assert NAMES[3] in message
    # 件数・行番号・列名を除くと数字も値も残らない
    rest = message.replace("1 件", "").replace(f"{LINE_OF_FIRST_ROW} 行目", "")
    rest = rest.replace(NAMES[3], "")
    assert not any(ch.isdigit() for ch in rest), message
    assert cell.strip() not in rest, message


def test_data_root_source_is_rejected() -> None:
    source = DatasetSource(records=[_record()], images_dir=Path("unused"), fingerprint=None)
    with pytest.raises(ValueError, match="data.bundle"):
        deeptias_feature_matrix(source)


def _with(column: str, value: str | None) -> dict[str, str | None]:
    values = _good_values()
    values[column] = value
    return values


def _without(column: str) -> dict[str, str | None]:
    values = _good_values()
    del values[column]
    return values


@pytest.mark.parametrize(
    "bad",
    [
        pytest.param(_without(NAMES[3]), id="column_missing"),
        pytest.param(_with(NAMES[3], None), id="empty"),
        pytest.param(_with(NAMES[3], ""), id="empty_string"),
        pytest.param(_with(NAMES[3], "abc"), id="not_a_number"),
        pytest.param(_with(NAMES[3], "nan"), id="nan"),
        pytest.param(_with(NAMES[3], "NaN"), id="nan_upper"),
        pytest.param(_with(NAMES[3], "inf"), id="inf"),
        pytest.param(_with(NAMES[3], "-inf"), id="minus_inf"),
        pytest.param(_with(NAMES[3], "Infinity"), id="infinity"),
        pytest.param(_with(NAMES[3], "1e999"), id="overflow"),
    ],
)
def test_bad_cell_stops_with_count_and_first_line(bad: dict) -> None:
    source = _source([_good_values(), bad, _good_values(), bad])
    with pytest.raises(ValueError) as excinfo:
        deeptias_feature_matrix(source)
    message = str(excinfo.value)
    assert "2 件" in message
    assert f"{LINE_OF_FIRST_ROW + 1} 行目" in message
    assert NAMES[3] in message
    _assert_no_identifiers(message)


def test_missing_annotation_kind_stops() -> None:
    with pytest.raises(ValueError) as excinfo:
        deeptias_feature_matrix(_source([None, _good_values()]))
    assert "1 件" in str(excinfo.value)
    assert f"{LINE_OF_FIRST_ROW} 行目" in str(excinfo.value)


def test_message_does_not_contain_the_bad_value() -> None:
    # 値は出さない（SPEC_02）．誤って別の列の値が入っていても手元のログに流れないように
    with pytest.raises(ValueError) as excinfo:
        deeptias_feature_matrix(_source([_with(NAMES[0], f"{SECRET}-{SHA}")]))
    _assert_no_identifiers(str(excinfo.value))


def test_row_with_several_problems_is_counted_once() -> None:
    bad = _with(NAMES[0], "x")
    bad[NAMES[1]] = None
    with pytest.raises(ValueError, match="1 件"):
        deeptias_feature_matrix(_source([bad]))


# --- 実ファイルのバンドル経由（load_dataset_source → deeptias_feature_matrix） ---


def _write_bundle(root: Path, columns: tuple[str, ...], rows: list[dict[str, str | None]]) -> None:
    (root / "files").mkdir(parents=True)
    entries = []
    for n, values in enumerate(rows):
        data = f"image{n}".encode()
        sha256 = hashlib.sha256(data).hexdigest()
        (root / "files" / f"{sha256}.png").write_bytes(data)
        entries.append(
            ManifestEntry(
                sha256=sha256,
                ext="png",
                kind="tongue_crop_masked",
                subject_id=f"{SECRET}{n}",
                capture_id=f"C{n:04d}",
                annotations={
                    "tongue_color": {"label": "red", "severity": "strong"},
                    "deeptias_features": values,
                },
            )
        )
    manifest = build_manifest(
        entries, {"tongue_color": ["label", "severity"], "deeptias_features": list(columns)}
    )
    (root / "manifest.csv").write_bytes(manifest)
    (root / "SHA256SUMS").write_bytes(
        build_sha256sums((e.sha256, f"files/{e.sha256}.{e.ext}") for e in entries)
    )
    info = BundleInfo(
        format=BUNDLE_FORMAT,
        name="tongue_color",
        version=3,
        created_at="2026-11-01T00:00:00Z",
        hub_commit="0000000",
        files=len(entries),
        manifest_sha256=manifest_sha256(manifest),
    )
    (root / "dataset.json").write_bytes(build_dataset_json(info))


def _load(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> DatasetSource:
    monkeypatch.setenv("TIASDATA_BUNDLES", str(tmp_path))
    return load_dataset_source(
        DataConfig.model_validate({"bundle": {"name": "tongue_color", "version": 3}})
    )


def test_real_bundle_rows_are_read_in_record_order(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    rows = [_good_values(float(100 * n)) for n in range(3)]
    _write_bundle(tmp_path / "tongue_color" / "v3", NAMES, rows)
    source = _load(tmp_path, monkeypatch)

    matrix = deeptias_feature_matrix(source)

    assert matrix.shape == (3, 15)
    # 行は source.records と同じ順（患者の番号と値の百の位を対応させてある）
    for record, row in zip(source.records, matrix, strict=True):
        n = int(record.patient_id.removeprefix(SECRET))
        np.testing.assert_array_equal(row, 100.0 * n + np.arange(15, dtype=np.float64))


def test_real_bundle_without_the_columns_stops_without_identifiers(
    tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
    # 版 2 までの manifest（DeepTIAS の列が無い）
    columns = NAMES[:-1]
    rows = [{name: "1.0" for name in columns} for _ in range(2)]
    _write_bundle(tmp_path / "tongue_color" / "v3", columns, rows)
    source = _load(tmp_path, monkeypatch)

    with pytest.raises(ValueError) as excinfo:
        deeptias_feature_matrix(source)
    message = str(excinfo.value)
    assert "2 件" in message
    assert NAMES[-1] in message
    assert SECRET not in message
    assert str(tmp_path) not in message
    assert ".png" not in message


def test_real_bundle_empty_cell_stops(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
    rows = [_good_values(), _with(NAMES[5], None)]
    _write_bundle(tmp_path / "tongue_color" / "v3", NAMES, rows)
    source = _load(tmp_path, monkeypatch)

    with pytest.raises(ValueError, match="1 件"):
        deeptias_feature_matrix(source)
