"""Tests para docx_to_markdown."""

import os
import sys
import tempfile

import pytest

sys.path.insert(0, os.path.dirname(__file__))

import docx as python_docx
from docx_to_markdown import docx_to_markdown


def _make_docx(builder_fn) -> str:
    """Create a temporary .docx file using builder_fn(doc) and return its path."""
    doc = python_docx.Document()
    builder_fn(doc)
    tmp = tempfile.NamedTemporaryFile(suffix=".docx", delete=False)
    doc.save(tmp.name)
    tmp.close()
    return tmp.name


# ---------------------------------------------------------------------------
# Tests
# ---------------------------------------------------------------------------


def test_docx_con_headings_y_parrafos():
    """docx con headings y parrafos"""

    def build(doc):
        doc.add_heading("Titulo Principal", level=1)
        doc.add_paragraph("Primer parrafo de contenido.")
        doc.add_heading("Seccion", level=2)
        doc.add_paragraph("Segundo parrafo.")

    path = _make_docx(build)
    try:
        result = docx_to_markdown(path)
        assert "# Titulo Principal" in result
        assert "## Seccion" in result
        assert "Primer parrafo de contenido." in result
        assert "Segundo parrafo." in result
    finally:
        os.unlink(path)


def test_docx_con_tablas_intercaladas():
    """docx con tablas intercaladas"""

    def build(doc):
        doc.add_paragraph("Texto antes de la tabla.")
        table = doc.add_table(rows=2, cols=3)
        table.cell(0, 0).text = "Col1"
        table.cell(0, 1).text = "Col2"
        table.cell(0, 2).text = "Col3"
        table.cell(1, 0).text = "a"
        table.cell(1, 1).text = "b"
        table.cell(1, 2).text = "c"
        doc.add_paragraph("Texto despues de la tabla.")

    path = _make_docx(build)
    try:
        result = docx_to_markdown(path)
        # Table must appear BETWEEN the two paragraphs
        before_idx = result.index("Texto antes de la tabla.")
        table_idx = result.index("| Col1")
        after_idx = result.index("Texto despues de la tabla.")
        assert before_idx < table_idx < after_idx
        assert "| Col2" in result
        assert "| a" in result
    finally:
        os.unlink(path)


def test_docx_con_formato_bold_italic():
    """docx con formato bold/italic"""

    def build(doc):
        para = doc.add_paragraph()
        run_bold = para.add_run("negrita")
        run_bold.bold = True
        run_normal = para.add_run(" texto normal ")
        run_italic = para.add_run("cursiva")
        run_italic.italic = True

    path = _make_docx(build)
    try:
        result = docx_to_markdown(path)
        assert "**negrita**" in result
        assert "*cursiva*" in result
        assert "texto normal" in result
    finally:
        os.unlink(path)


def test_docx_vacio():
    """docx vacio"""

    def build(doc):
        # python-docx adds a default empty paragraph; remove all content
        # by just not adding anything — the default empty paragraph will
        # produce an empty string that gets filtered out.
        pass

    path = _make_docx(build)
    try:
        result = docx_to_markdown(path)
        # Empty document should produce empty or whitespace-only output
        assert result.strip() == ""
    finally:
        os.unlink(path)


def test_archivo_no_encontrado():
    """archivo no encontrado lanza FileNotFoundError"""
    with pytest.raises(FileNotFoundError):
        docx_to_markdown("/tmp/nonexistent_file_fn_registry.docx")


if __name__ == "__main__":
    test_docx_con_headings_y_parrafos()
    test_docx_con_tablas_intercaladas()
    test_docx_con_formato_bold_italic()
    test_docx_vacio()
    test_archivo_no_encontrado()
    print("All tests passed.")
