"""Integration tests for XLSX parser."""

from __future__ import annotations

import importlib.util

import pytest

pytestmark = pytest.mark.skipif(
    importlib.util.find_spec("openpyxl") is None, reason="openpyxl not installed"
)

from extractor import extract
from extractor.schema import ELEMENT_TYPES


def test_xlsx_no_crash(xlsx_fixture):
    assert len(list(extract(xlsx_fixture, mode="elements"))) > 0


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


def test_xlsx_chunks_mode(xlsx_fixture):
    assert len(list(extract(xlsx_fixture, mode="chunks"))) > 0


def test_xlsx_required_fields(xlsx_fixture):
    for el in extract(xlsx_fixture, mode="elements"):
        assert el.id and el.source_filename and el.schema_version


def test_xlsx_has_sheet_heading(xlsx_fixture):
    """XLSX emits sheet names as section headers."""
    elements = list(extract(xlsx_fixture, mode="elements"))
    types = [e.element_type for e in elements]
    assert "structural:section_header" in types


def test_xlsx_multi_sheet(xlsx_fixture):
    elements = list(extract(xlsx_fixture, mode="elements"))
    tables = [e for e in elements if e.element_type in ("table:simple", "table:complex")]
    # 2 sheets -> at least 2 table elements
    assert len(tables) >= 2


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

    p = Path(__file__).parent.parent.parent / "sample_data" / "financials.xlsx"
    if not p.exists():
        pytest.skip("sample_data/financials.xlsx 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)),
        }
    )
