"""Tests for the validation hook (Camelot-vs-LLM table count)."""

from pathlib import Path

from quber.agents.llm_client import MockLLMClient
from quber.core.extractors import ExtractedTable
from quber.core.validate import camelot_counts_by_page, camelot_vs_llm_count_sync


def _fake_image(tmp_path: Path, page: int) -> Path:
    p = tmp_path / f"page-{page:04d}.png"
    p.write_bytes(b"\x89PNG\r\n\x1a\n")
    return p


def test_camelot_counts_by_page():
    tables = [
        ExtractedTable(markdown="x", page=1),
        ExtractedTable(markdown="x", page=1),
        ExtractedTable(markdown="x", page=3),
    ]
    assert camelot_counts_by_page(tables) == {1: 2, 3: 1}


def test_validate_no_mismatch(tmp_path: Path):
    images = [_fake_image(tmp_path, i) for i in range(1, 3)]
    tables = [
        ExtractedTable(markdown="x", page=1),
        ExtractedTable(markdown="x", page=2),
    ]
    llm = MockLLMClient(table_count=1)

    report = camelot_vs_llm_count_sync(Path("doc.pdf"), tables, images, llm)
    assert report.has_mismatches is False
    assert report.pages_checked == 2
    assert report.total_pages == 2
    assert report.errors == []


def test_validate_detects_mismatch(tmp_path: Path):
    images = [_fake_image(tmp_path, i) for i in range(1, 3)]
    tables = [ExtractedTable(markdown="x", page=1)]  # camelot found 1 on page 1, 0 on page 2
    llm = MockLLMClient(table_count=2)  # llm says 2 tables on each page

    report = camelot_vs_llm_count_sync(Path("doc.pdf"), tables, images, llm)
    assert report.has_mismatches is True
    assert len(report.mismatches) == 2

    p1 = next(m for m in report.mismatches if m.page == 1)
    assert p1.camelot_count == 1
    assert p1.llm_count == 2
    assert p1.delta == 1


def test_validate_out_of_range_page_reports_error(tmp_path: Path):
    images = [_fake_image(tmp_path, 1)]
    tables: list[ExtractedTable] = []
    llm = MockLLMClient()
    report = camelot_vs_llm_count_sync(Path("doc.pdf"), tables, images, llm, pages=[1, 99])
    assert any("99" in e for e in report.errors)
