from __future__ import annotations

from pathlib import Path

from crowley_diary.source import SourcePackage
from crowley_diary.util import load_json, project_root


def test_literal_tsv_parser_does_not_treat_quotes_as_csv(source_root: Path) -> None:
    source = SourcePackage(source_root)
    assert len(source.tsv_words(6)) == 407
    assert len(source.tsv_words(278)) == 419
    assert source.manifest_by_page[278]["ocr_word_count"] == 35


def test_source_audit_records_known_metric_problem(source_root: Path) -> None:
    report = SourcePackage(source_root).verify()
    assert report["summary"]["word_count_mismatches"] == 50
    assert report["summary"]["major_word_count_mismatches"] == 21
    assert report["errors"] == []


def test_evaluation_selection_loads_existing_source_files(source_root: Path) -> None:
    source = SourcePackage(source_root)
    selection = load_json(project_root() / "evaluation" / "selection.json")
    pages = [case["page"] for case in selection["cases"]]
    assert len(pages) == 14
    assert len(set(pages)) == 14
    for page in pages:
        assert source.image_path(page).is_file()
        assert source.ocr_text_path(page).is_file()
        assert source.ocr_tsv_path(page).is_file()


def test_successful_candidate_index_is_complete_and_loadable() -> None:
    index = load_json(project_root() / "evaluation" / "candidate-index.json")
    records = index["candidates"]
    assert len(records) == 14
    assert len({record["page"] for record in records}) == 14
    for record in records:
        path = project_root() / record["path"]
        candidate = load_json(path)
        assert candidate["source"]["pdf_page"] == record["page"]
        assert candidate["review"]["status"] == "model_candidate"
        assert candidate["review"]["authority"] == "diagnostic_only"


def test_book_segment_map_preserves_gap(source_root: Path) -> None:
    source = SourcePackage(source_root)
    assert source.segment_for_page(109)["kind"] == "separator"
    assert source.segment_for_page(110)["kind"] == "source_gap"
    assert source.segment_for_page(111)["id"] == "book-05"
