"""Integration tests for DOCX parser."""

from __future__ import annotations

import importlib.util

import pytest

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

from extractor import extract
from extractor.schema import ELEMENT_TYPES


def test_docx_no_crash(docx_fixture):
    assert len(list(extract(docx_fixture, mode="elements"))) > 0


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


def test_docx_chunks_mode(docx_fixture):
    assert len(list(extract(docx_fixture, mode="chunks"))) > 0


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


def test_docx_has_heading(docx_fixture):
    elements = list(extract(docx_fixture, mode="elements"))
    headings = [e for e in elements if e.element_type == "structural:section_header"]
    assert len(headings) >= 1


def test_docx_has_table(docx_fixture):
    elements = list(extract(docx_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


def test_docx_table_data_populated(docx_fixture):
    elements = list(extract(docx_fixture, mode="elements"))
    tables = [e for e in elements if e.element_type in ("table:simple", "table:complex")]
    t = tables[0].table
    assert t.col_count == 3
    assert t.row_count == 2


def test_docx_merged_table_is_complex(docx_merged_fixture):
    """DOCX with merged cells is detected as table:complex."""
    elements = list(extract(docx_merged_fixture, mode="elements"))
    tables = [e for e in elements if e.element_type in ("table:simple", "table:complex")]
    assert len(tables) >= 1
    t = tables[0]
    assert t.element_type == "table:complex"
    assert t.table is not None
    assert len(t.table.merge_map) > 0
