"""目録の集計（`tiasdata stats`．SPEC_03「CLI」）.

- 種類・所見の値ごとの件数を返す
- 対応表を開かない（SPEC_02「対応表」: 対応表を開くのは取り込みのときだけ）
"""

import json
import sqlite3
from contextlib import closing

import pytest
from conftest import ImportEnv, deeptias_names, deeptias_values

from tiasdata.cli import main
from tiasdata.config import load_config
from tiasdata.importers import run_import
from tiasdata.stats import collect_stats


def _open(env: ImportEnv) -> sqlite3.Connection:
    return sqlite3.connect(env.catalog_root / "catalog.sqlite")


def test_empty_catalog(import_env: ImportEnv) -> None:
    assert main(["init"]) == 0
    with closing(_open(import_env)) as conn:
        stats = collect_stats(conn)
    assert stats.subjects == 0
    assert stats.captures == 0
    assert stats.subjects_with_multiple_captures == 0
    assert set(stats.assets_by_kind.values()) == {0}
    assert "tongue_crop_masked" in stats.assets_by_kind
    assert stats.annotations == {}
    assert stats.superseded_annotations == 0


def test_counts_after_import(import_env: ImportEnv) -> None:
    assert main(["init"]) == 0
    run_import(load_config(import_env.config_path), import_env.source_name)
    with closing(_open(import_env)) as conn:
        stats = collect_stats(conn)
    assert stats.subjects == 7
    assert stats.captures == 18
    # ダミーの 7 人はみな 2 枚以上
    assert stats.subjects_with_multiple_captures == 7
    assert stats.assets_by_kind == {
        "color_chart": 0,
        "deeptias_output_file": 0,
        "tongue_crop_masked": 18,
        "tongue_mask": 0,
        "tongue_raw": 0,
        "tongue_seg_fullsize_image": 0,
        "tongue_seg_fullsize_mask": 0,
        "tongue_seg_image": 0,
    }
    tongue = stats.annotations["tongue_color"]
    assert tongue.total == 18
    assert tongue.by_field["label"] == {
        "dark_red": 4,
        "light_red": 2,
        "pale": 4,
        "purple": 4,
        "red": 4,
    }
    assert tongue.by_field["severity"] == {"mild": 8, "normal": 2, "strong": 8}
    # 9 フォルダ（ラベル×程度の組み合わせ）ごとに 2 枚
    assert len(tongue.by_value) == 9
    assert set(tongue.by_value.values()) == {2}
    assert stats.superseded_annotations == 0


def test_stats_does_not_need_identity_db(import_env: ImportEnv) -> None:
    assert main(["init"]) == 0
    run_import(load_config(import_env.config_path), import_env.source_name)
    import_env.identity_path.unlink()
    assert main(["stats"]) == 0
    assert not import_env.identity_path.exists()


def test_reviewed_images_are_counted_with_marks(import_env: ImportEnv) -> None:
    # 2026-10-08 の仕様変更: 要確認の番号も登録し，撮影に要確認の印を付ける
    from conftest import write_reviews

    write_reviews(import_env.reviews_dir, "dummy_tongue", [1, 2])  # light_red の 2 枚
    assert main(["init"]) == 0
    run_import(load_config(import_env.config_path), import_env.source_name)
    with closing(_open(import_env)) as conn:
        stats = collect_stats(conn)
    assert stats.captures == 18
    assert stats.review_marks_on_captures == 2
    assert stats.review_marks_on_files == 0
    assert stats.assets_without_capture == 0


def _share_first_image(env: ImportEnv, number: int) -> None:
    # 番号 1 と同じ中身を同じフォルダ（同じラベル）に置き，対応表に行を足す
    from conftest import write_patient_map

    first = env.source.images[0]
    (first.path.parent / f"{number}.png").write_bytes(first.path.read_bytes())
    rows = [(n, 1, key) for n, key in sorted(env.patient_map.patient_keys.items())]
    write_patient_map(env.patient_map.path, [*rows, (number, 1, "990088")])


def test_unlinked_files_and_review_marks_are_counted(import_env: ImportEnv) -> None:
    # 2026-10-08: 撮影にひも付かないファイルの件数，review の印の件数（撮影・ファイル）．
    # review は所見の種類ごとの内訳に入れない
    from conftest import write_reviews

    _share_first_image(import_env, 19)
    write_reviews(import_env.reviews_dir, "dummy_tongue", [1, 5, 19])
    assert main(["init"]) == 0
    run_import(load_config(import_env.config_path), import_env.source_name)
    with closing(_open(import_env)) as conn:
        stats = collect_stats(conn)
    assert stats.captures == 17
    assert stats.assets_by_kind["tongue_crop_masked"] == 18
    assert stats.assets_without_capture == 1
    assert stats.review_marks_on_captures == 1
    assert stats.review_marks_on_files == 1
    assert set(stats.annotations) == {"tongue_color"}
    # 撮影 17 件と撮影にひも付かないファイル 1 件の舌色
    assert stats.annotations["tongue_color"].total == 18


def test_superseded_review_mark_is_not_counted(import_env: ImportEnv) -> None:
    from conftest import write_reviews

    write_reviews(import_env.reviews_dir, "dummy_tongue", [1, 2])
    assert main(["init"]) == 0
    run_import(load_config(import_env.config_path), import_env.source_name)
    with closing(_open(import_env)) as conn:
        ids = [
            i
            for (i,) in conn.execute(
                "SELECT annotation_id FROM annotations WHERE kind = 'review' ORDER BY annotation_id"
            )
        ]
        conn.execute(
            "UPDATE annotations SET superseded_by = ? WHERE annotation_id = ?", (ids[1], ids[0])
        )
        conn.commit()
        stats = collect_stats(conn)
    assert stats.review_marks_on_captures == 1
    assert stats.review_marks_on_files == 0
    assert stats.superseded_annotations == 1


def test_empty_catalog_has_no_unlinked_or_marks(import_env: ImportEnv) -> None:
    assert main(["init"]) == 0
    with closing(_open(import_env)) as conn:
        stats = collect_stats(conn)
    assert stats.assets_without_capture == 0
    assert stats.review_marks_on_captures == 0
    assert stats.review_marks_on_files == 0


# ---------------------------------------------------------------------------
# deeptias_output_file は「撮影にひも付かないファイル」に数えない（SPEC_02「kinds」）
# ---------------------------------------------------------------------------
def _add_output_file(conn: sqlite3.Connection, seed: str) -> None:
    conn.execute(
        "INSERT INTO assets (sha256, kind, capture_id, ext, size_bytes, source, source_name,"
        " registered_at) VALUES (?, 'deeptias_output_file', NULL, 'csv', 1, 'x', ?,"
        " '2026-11-01T00:00:00Z')",
        (seed * 64, f"1/{seed}.csv"),
    )


def test_output_files_are_not_counted_as_unlinked(
    import_env: ImportEnv, capsys: pytest.CaptureFixture[str]
) -> None:
    from conftest import write_reviews

    # 撮影にひも付かない舌色の画像 1 つと，出力のファイル 2 つ
    _share_first_image(import_env, 19)
    write_reviews(import_env.reviews_dir, "dummy_tongue", [1, 19])
    assert main(["init"]) == 0
    run_import(load_config(import_env.config_path), import_env.source_name)
    with closing(_open(import_env)) as conn:
        _add_output_file(conn, "a")
        _add_output_file(conn, "b")
        conn.commit()
        stats = collect_stats(conn)
    assert stats.assets_without_capture == 1
    # 種類ごとのファイル数には出す
    assert stats.assets_by_kind["deeptias_output_file"] == 2


# ---------------------------------------------------------------------------
# tongue_color_rounds は件数と 3 回とも同じクラスの数だけ（SPEC_03「CLI」の stats）
# ---------------------------------------------------------------------------
def _rounds(*rounds: tuple[str, int] | None) -> str:
    return json.dumps(
        {"rounds": [r if r is None else {"label": r[0], "level": r[1]} for r in rounds]}
    )


# 3 回とも同じクラスは 2 件（程度は問わない．null を含むものは数えない）
_ROUND_VALUES = [
    _rounds(("pale", 1), ("pale", 1), ("pale", 1)),
    _rounds(("red", 1), ("red", 2), ("red", 3)),
    _rounds(("red", 1), ("red", 1), ("purple", 1)),
    _rounds(("red", 1), ("red", 1), None),
    _rounds(None, None, None),
    _rounds(None, ("dark_red", 2), ("dark_red", 2)),
]


class TestRoundsAreSummarized:
    @pytest.fixture
    def env(self, import_env: ImportEnv) -> ImportEnv:
        assert main(["init"]) == 0
        run_import(load_config(import_env.config_path), import_env.source_name)
        with closing(_open(import_env)) as conn:
            captures = [c for (c,) in conn.execute("SELECT capture_id FROM captures LIMIT 6")]
            for capture_id, value in zip(captures, _ROUND_VALUES, strict=True):
                conn.execute(
                    "INSERT INTO annotations (kind, capture_id, value, source, created_at)"
                    " VALUES ('tongue_color_rounds', ?, ?, 'namiki_label_xlsx',"
                    " '2026-11-01T00:00:00Z')",
                    (capture_id, value),
                )
            conn.commit()
        return import_env

    def test_summary(self, env: ImportEnv) -> None:
        with closing(_open(env)) as conn:
            stats = collect_stats(conn)
        summary = stats.annotations["tongue_color_rounds"]
        assert summary.total == 6
        assert summary.by_field == {}
        assert summary.by_value == {}
        assert stats.rounds_all_same_class == 2

    def test_same_value_on_many_captures_is_counted_each(self, env: ImportEnv) -> None:
        with closing(_open(env)) as conn:
            capture_id = conn.execute(
                "SELECT capture_id FROM captures WHERE capture_id NOT IN"
                " (SELECT capture_id FROM annotations WHERE kind = 'tongue_color_rounds')"
                " LIMIT 1"
            ).fetchone()[0]
            conn.execute(
                "INSERT INTO annotations (kind, capture_id, value, source, created_at)"
                " VALUES ('tongue_color_rounds', ?, ?, 'namiki_label_xlsx',"
                " '2026-11-01T00:00:00Z')",
                (capture_id, _ROUND_VALUES[0]),
            )
            conn.commit()
            assert collect_stats(conn).rounds_all_same_class == 3

    def test_no_rounds_is_zero(self, import_env: ImportEnv) -> None:
        assert main(["init"]) == 0
        with closing(_open(import_env)) as conn:
            assert collect_stats(conn).rounds_all_same_class == 0

    def test_cli_shows_only_the_counts(
        self, env: ImportEnv, capsys: pytest.CaptureFixture[str]
    ) -> None:
        capsys.readouterr()
        assert main(["stats"]) == 0
        out = capsys.readouterr().out
        assert "tongue_color_rounds: 6 件" in out
        assert "3 回とも同じクラス: 2 件" in out
        # 値ごとの内訳を出さない
        assert '"rounds"' not in out
        assert "level" not in out

    def test_cli_does_not_show_the_line_without_rounds(
        self, import_env: ImportEnv, capsys: pytest.CaptureFixture[str]
    ) -> None:
        assert main(["init"]) == 0
        run_import(load_config(import_env.config_path), import_env.source_name)
        capsys.readouterr()
        assert main(["stats"]) == 0
        assert "3 回とも同じクラス" not in capsys.readouterr().out


# ---------------------------------------------------------------------------
# deeptias_features は件数だけ（SPEC_03「CLI」の stats）
# ---------------------------------------------------------------------------
def _add_features(conn: sqlite3.Connection, seeds_and_captures: list[tuple[int, str]]) -> None:
    for seed, capture_id in seeds_and_captures:
        conn.execute(
            "INSERT INTO annotations (kind, capture_id, value, source, created_at)"
            " VALUES ('deeptias_features', ?, ?, 'deeptias_output_folder',"
            " '2026-10-31T00:00:00Z')",
            (capture_id, json.dumps(deeptias_values(seed))),
        )
    conn.commit()


class TestDeepTiasFeaturesAreCountOnly:
    @pytest.fixture
    def env(self, import_env: ImportEnv) -> ImportEnv:
        assert main(["init"]) == 0
        run_import(load_config(import_env.config_path), import_env.source_name)
        with closing(_open(import_env)) as conn:
            captures = [c for (c,) in conn.execute("SELECT capture_id FROM captures LIMIT 3")]
            _add_features(conn, [(i + 1, capture) for i, capture in enumerate(captures)])
        return import_env

    def test_summary_has_total_and_no_breakdown(self, env: ImportEnv) -> None:
        with closing(_open(env)) as conn:
            stats = collect_stats(conn)
        summary = stats.annotations["deeptias_features"]
        assert summary.total == 3
        assert summary.by_field == {}
        assert summary.by_value == {}
        # 他の種類は今までどおり内訳を出す
        assert stats.annotations["tongue_color"].by_field["label"]
        assert stats.annotations["tongue_color"].by_value

    def test_cli_shows_only_the_count(
        self, env: ImportEnv, capsys: pytest.CaptureFixture[str]
    ) -> None:
        capsys.readouterr()
        assert main(["stats"]) == 0
        out = capsys.readouterr().out
        lines = [line for line in out.splitlines() if "deeptias_features" in line]
        assert [line.strip() for line in lines] == ["deeptias_features: 3 件"]
        for name in deeptias_names():
            assert name not in out
        for seed in (1, 2, 3):
            for value in deeptias_values(seed).values():
                assert repr(value) not in out
        # 舌色の内訳は出る
        assert "組み合わせ:" in out

    def test_superseded_features_are_not_counted(self, env: ImportEnv) -> None:
        with closing(_open(env)) as conn:
            [old, new] = [
                row[0]
                for row in conn.execute(
                    "SELECT annotation_id FROM annotations"
                    " WHERE kind = 'deeptias_features' ORDER BY annotation_id LIMIT 2"
                )
            ]
            conn.execute(
                "UPDATE annotations SET superseded_by = ? WHERE annotation_id = ?", (new, old)
            )
            conn.commit()
            stats = collect_stats(conn)
        assert stats.annotations["deeptias_features"].total == 2
        assert stats.superseded_annotations == 1


# ---------------------------------------------------------------------------
# tongue_color_first_round は件数と label・level ごと・組み合わせごとの内訳
# （SPEC_03「舌色の 1 回目のラベル」）
# ---------------------------------------------------------------------------
_FIRST_ROUND_VALUES = [
    ("pale", 2),
    ("pale", 2),
    ("pale", 3),
    ("red", 1),
    ("light_red", 1),
]


class TestFirstRoundIsSummarized:
    @pytest.fixture
    def env(self, import_env: ImportEnv) -> ImportEnv:
        assert main(["init"]) == 0
        run_import(load_config(import_env.config_path), import_env.source_name)
        with closing(_open(import_env)) as conn:
            captures = [c for (c,) in conn.execute("SELECT capture_id FROM captures LIMIT 5")]
            for capture_id, (label, level) in zip(captures, _FIRST_ROUND_VALUES, strict=True):
                conn.execute(
                    "INSERT INTO annotations (kind, capture_id, value, source, created_at)"
                    " VALUES ('tongue_color_first_round', ?, ?, 'namiki_first_round_xlsx',"
                    " '2026-11-02T00:00:00Z')",
                    (capture_id, json.dumps({"label": label, "level": level})),
                )
            conn.commit()
        return import_env

    def test_summary(self, env: ImportEnv) -> None:
        with closing(_open(env)) as conn:
            summary = collect_stats(conn).annotations["tongue_color_first_round"]
        assert summary.total == 5
        assert summary.by_field == {
            "label": {"light_red": 1, "pale": 3, "red": 1},
            "level": {"1": 2, "2": 2, "3": 1},
        }
        assert summary.by_value == {
            "label=light_red, level=1": 1,
            "label=pale, level=2": 2,
            "label=pale, level=3": 1,
            "label=red, level=1": 1,
        }

    def test_cli_shows_counts_and_breakdown(
        self, env: ImportEnv, capsys: pytest.CaptureFixture[str]
    ) -> None:
        capsys.readouterr()
        assert main(["stats"]) == 0
        out = capsys.readouterr().out
        assert "tongue_color_first_round: 5 件" in out
        assert "label: light_red 1・pale 3・red 1" in out
        assert "level: 1 2・2 2・3 1" in out
        assert "label=pale, level=2: 2 件" in out
        assert "label=light_red, level=1: 1 件" in out


def test_captures_without_subject_are_counted(import_env: ImportEnv) -> None:
    # catalog/0006: 症例の無い撮影（セグメンテーション等）は撮影に数え，別に数を出す．
    # 撮影が 2 つ以上の症例には数えない
    assert main(["init"]) == 0
    run_import(load_config(import_env.config_path), import_env.source_name)
    with closing(_open(import_env)) as conn:
        conn.executemany(
            "INSERT INTO captures (capture_id, subject_id) VALUES (?, NULL)",
            [("C000901",), ("C000902",)],
        )
        conn.commit()
        stats = collect_stats(conn)
    assert stats.captures == 20
    assert stats.captures_without_subject == 2
    assert stats.subjects == 7
    assert stats.subjects_with_multiple_captures == 7


def test_stats_output_line_for_captures(
    import_env: ImportEnv, capsys: pytest.CaptureFixture[str]
) -> None:
    assert main(["init"]) == 0
    run_import(load_config(import_env.config_path), import_env.source_name)
    capsys.readouterr()
    assert main(["stats"]) == 0
    assert "撮影: 18 件（症例にひも付かない撮影: 0 件）" in capsys.readouterr().out
