"""Integration tests for CSV parser."""

from __future__ import annotations

import pytest

from extractor import extract
from extractor.schema import ELEMENT_TYPES


def test_csv_no_crash(csv_fixture):
    elements = list(extract(csv_fixture, mode="elements"))
    assert len(elements) > 0


def test_csv_element_types_valid(csv_fixture):
    for el in extract(csv_fixture, mode="elements"):
        assert el.element_type in ELEMENT_TYPES


def test_csv_chunks_mode(csv_fixture):
    chunks = list(extract(csv_fixture, mode="chunks"))
    assert len(chunks) > 0


def test_csv_required_fields(csv_fixture):
    for el in extract(csv_fixture, mode="elements"):
        assert el.id
        assert el.source_filename
        assert el.schema_version


def test_csv_has_document_title(csv_fixture):
    elements = list(extract(csv_fixture, mode="elements"))
    types = [e.element_type for e in elements]
    assert "meta:document_title" in types


def test_csv_has_table(csv_fixture):
    elements = list(extract(csv_fixture, mode="elements"))
    tables = [e for e in elements if e.element_type in ("table:simple", "table:complex")]
    assert len(tables) >= 1
    assert tables[0].table is not None
    assert tables[0].table.row_count == 3  # 3 data rows


def test_csv_regression(data_regression):
    from collections import Counter
    from pathlib import Path

    p = Path(__file__).parent.parent.parent / "sample_data" / "data.csv"
    if not p.exists():
        pytest.skip("sample_data/data.csv not found")
    elements = list(extract(p, mode="elements"))
    data_regression.check(
        {
            "total": len(elements),
            "by_type": dict(Counter(e.element_type for e in elements)),
        }
    )
