"""Integration tests for PDF parser."""

from __future__ import annotations

import importlib.util

import pytest

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

from extractor import extract
from extractor.schema import ELEMENT_TYPES


def test_pdf_no_crash(pdf_fixture):
    assert len(list(extract(pdf_fixture, mode="elements"))) > 0


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


def test_pdf_chunks_mode(pdf_fixture):
    assert len(list(extract(pdf_fixture, mode="chunks"))) > 0


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


def test_pdf_has_headings(pdf_fixture):
    elements = list(extract(pdf_fixture, mode="elements"))
    # PDF may produce headings or narrative depending on extraction strategy
    structural = [
        e
        for e in elements
        if e.element_type in ("structural:section_header", "structural:title", "text:narrative")
    ]
    assert len(structural) >= 1


def test_pdf_has_narrative(pdf_fixture):
    elements = list(extract(pdf_fixture, mode="elements"))
    narratives = [e for e in elements if e.element_type == "text:narrative"]
    assert len(narratives) >= 1


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

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