"""
Integration test fixtures — programmatic generation, no binary blobs in git.
Session-scoped so fixtures are created once per test run.
"""

from __future__ import annotations

import json
from pathlib import Path

import pytest

SAMPLE_DATA = Path(__file__).parent.parent.parent / "sample_data"


# ---------------------------------------------------------------------------
# Programmatic fixtures (no binary files committed)
# ---------------------------------------------------------------------------


@pytest.fixture(scope="session")
def csv_fixture(tmp_path_factory):
    p = tmp_path_factory.mktemp("fixtures") / "minimal.csv"
    p.write_text("name,age,city\nAlice,30,London\nBob,25,Paris\nCarol,35,Berlin\n")
    return p


@pytest.fixture(scope="session")
def md_fixture(tmp_path_factory):
    p = tmp_path_factory.mktemp("fixtures") / "minimal.md"
    p.write_text(
        "# Main Heading\n\nA paragraph of text.\n\n## Section Two\n\nAnother paragraph.\n\n"
        "```python\nprint('hello')\n```\n\n- bullet one\n- bullet two\n"
    )
    return p


@pytest.fixture(scope="session")
def html_fixture(tmp_path_factory):
    p = tmp_path_factory.mktemp("fixtures") / "minimal.html"
    p.write_text(
        "<html><body>"
        "<h1>Main Title</h1>"
        "<h2>Section</h2>"
        "<p>A paragraph of text.</p>"
        "<table><tr><th>Col A</th><th>Col B</th></tr>"
        "<tr><td>1</td><td>2</td></tr></table>"
        "</body></html>"
    )
    return p


@pytest.fixture(scope="session")
def json_fixture(tmp_path_factory):
    p = tmp_path_factory.mktemp("fixtures") / "minimal.json"
    data = {
        "title": "Test Document",
        "metadata": {"author": "Test", "version": "1.0"},
        "content": "Some narrative text here.",
        "items": ["item one", "item two"],
    }
    p.write_text(json.dumps(data, indent=2))
    return p


@pytest.fixture(scope="session")
def xml_fixture(tmp_path_factory):
    p = tmp_path_factory.mktemp("fixtures") / "minimal.xml"
    p.write_text(
        '<?xml version="1.0" encoding="UTF-8"?>\n'
        "<document>\n"
        "  <title>Test Document</title>\n"
        "  <section>\n"
        "    <heading>Introduction</heading>\n"
        "    <paragraph>Some text content here.</paragraph>\n"
        "  </section>\n"
        "</document>\n"
    )
    return p


@pytest.fixture(scope="session")
def txt_fixture(tmp_path_factory):
    p = tmp_path_factory.mktemp("fixtures") / "minimal.txt"
    p.write_text(
        "This is a plain text document.\n\nIt has multiple paragraphs.\n\nAnd a third one.\n"
    )
    return p


@pytest.fixture(scope="session")
def docx_fixture(tmp_path_factory):
    from docx import Document

    p = tmp_path_factory.mktemp("fixtures") / "minimal.docx"
    doc = Document()
    doc.add_heading("Test Document Heading", level=1)
    doc.add_paragraph("A test paragraph with sufficient text content for extraction.")
    doc.add_heading("Section Two", level=2)
    doc.add_paragraph("Second section paragraph.")
    # Simple table
    table = doc.add_table(rows=3, cols=3)
    table.cell(0, 0).text = "Header A"
    table.cell(0, 1).text = "Header B"
    table.cell(0, 2).text = "Header C"
    table.cell(1, 0).text = "Row1A"
    table.cell(1, 1).text = "Row1B"
    table.cell(1, 2).text = "Row1C"
    table.cell(2, 0).text = "Row2A"
    table.cell(2, 1).text = "Row2B"
    table.cell(2, 2).text = "Row2C"
    doc.save(p)
    return p


@pytest.fixture(scope="session")
def docx_merged_fixture(tmp_path_factory):
    """DOCX with merged cells for table:complex testing."""
    from docx import Document

    p = tmp_path_factory.mktemp("fixtures") / "merged.docx"
    doc = Document()
    doc.add_heading("Document with Merged Table", level=1)
    table = doc.add_table(rows=3, cols=3)
    # Merge first row across all columns
    cell_a = table.cell(0, 0)
    cell_c = table.cell(0, 2)
    cell_a.merge(cell_c)
    cell_a.text = "Merged Header"
    table.cell(1, 0).text = "A"
    table.cell(1, 1).text = "B"
    table.cell(1, 2).text = "C"
    table.cell(2, 0).text = "D"
    table.cell(2, 1).text = "E"
    table.cell(2, 2).text = "F"
    doc.save(p)
    return p


@pytest.fixture(scope="session")
def xlsx_fixture(tmp_path_factory):
    import openpyxl

    p = tmp_path_factory.mktemp("fixtures") / "minimal.xlsx"
    wb = openpyxl.Workbook()
    ws1 = wb.active
    ws1.title = "Sheet1"
    ws1.append(["Name", "Value", "Category"])
    ws1.append(["Alpha", 10, "A"])
    ws1.append(["Beta", 20, "B"])
    ws1.append(["Gamma", 30, "C"])
    ws2 = wb.create_sheet("Sheet2")
    ws2.append(["X", "Y"])
    ws2.append([1, 2])
    wb.save(p)
    return p


@pytest.fixture(scope="session")
def pptx_fixture(tmp_path_factory):
    from pptx import Presentation
    from pptx.util import Inches

    p = tmp_path_factory.mktemp("fixtures") / "minimal.pptx"
    prs = Presentation()
    # Slide 1: title
    slide1 = prs.slides.add_slide(prs.slide_layouts[0])
    slide1.shapes.title.text = "Presentation Title"
    slide1.placeholders[1].text = "Subtitle text"
    # Slide 2: content
    slide2 = prs.slides.add_slide(prs.slide_layouts[1])
    slide2.shapes.title.text = "Content Slide"
    tf = slide2.placeholders[1].text_frame
    tf.text = "First bullet"
    tf.add_paragraph().text = "Second bullet"
    # Slide 3: table
    slide3 = prs.slides.add_slide(prs.slide_layouts[5])
    slide3.shapes.title.text = "Table Slide"
    rows, cols = 3, 3
    table = slide3.shapes.add_table(rows, cols, Inches(1), Inches(1.5), Inches(8), Inches(3)).table
    for c in range(cols):
        table.cell(0, c).text = f"H{c + 1}"
    for r in range(1, rows):
        for c in range(cols):
            table.cell(r, c).text = f"R{r}C{c + 1}"
    prs.save(p)
    return p


@pytest.fixture(scope="session")
def pdf_fixture():
    """Use existing sample_data PDF."""
    p = SAMPLE_DATA / "systems_design.pdf"
    if not p.exists():
        pytest.skip("sample_data/systems_design.pdf not found")
    return p


@pytest.fixture(scope="session")
def epub_fixture():
    """Use static minimal EPUB fixture."""
    p = Path(__file__).parent / "fixtures" / "minimal.epub"
    if not p.exists():
        pytest.skip("tests/integration/fixtures/minimal.epub not found")
    return p


@pytest.fixture(scope="session")
def latex_fixture():
    """Use static minimal LaTeX fixture."""
    p = Path(__file__).parent / "fixtures" / "minimal.tex"
    if not p.exists():
        pytest.skip("tests/integration/fixtures/minimal.tex not found")
    return p
