"""Integration tests for Markdown parser."""

from __future__ import annotations

import pytest

from extractor import extract
from extractor.schema import ELEMENT_TYPES


def test_md_no_crash(md_fixture):
    assert len(list(extract(md_fixture, mode="elements"))) > 0


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


def test_md_chunks_mode(md_fixture):
    assert len(list(extract(md_fixture, mode="chunks"))) > 0


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


def test_md_headings_have_levels(md_fixture):
    elements = list(extract(md_fixture, mode="elements"))
    headings = [e for e in elements if e.element_type == "structural:section_header"]
    assert len(headings) >= 1
    for h in headings:
        # Heading depth is encoded in section_path_tier (1-4)
        assert 1 <= h.section_path_tier <= 4


def test_md_code_block(md_fixture):
    elements = list(extract(md_fixture, mode="elements"))
    types = [e.element_type for e in elements]
    assert "code:block" in types


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

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