"""DocumentConverter: page/sheet range, images_* directory."""

from __future__ import annotations

from pathlib import Path

import openpyxl
import pytest

from aicd.tools.docs_convert import DocumentConverter


def _noop_policy(_p: Path) -> None:
    return None


@pytest.fixture
def converter() -> DocumentConverter:
    return DocumentConverter(_noop_policy)


def test_pdf_page_range(converter: DocumentConverter, tmp_path: Path) -> None:
    import fitz

    pdf = tmp_path / "two_pages.pdf"
    doc = fitz.open()
    doc.new_page()
    doc[0].insert_text((72, 72), "hello page1")
    doc.new_page()
    doc[1].insert_text((72, 72), "hello page2")
    doc.save(pdf)
    doc.close()

    out = tmp_path / "out_pdf"
    r = converter.convert_document(
        str(pdf),
        str(out),
        output_format="markdown",
        page_start=1,
        page_end=1,
    )
    assert r["ok"] is True
    text = Path(r["output_path"]).read_text(encoding="utf-8")
    assert "hello page1" in text
    assert "hello page2" not in text
    assert Path(r["images_dir"]).is_dir()
    assert r["images_relative_prefix"] == "images_two_pages"


def test_xlsx_sheet_range(converter: DocumentConverter, tmp_path: Path) -> None:
    xlsx = tmp_path / "wb.xlsx"
    wb = openpyxl.Workbook()
    wb.active.title = "A"
    wb.create_sheet("B")
    wb.create_sheet("C")
    for name in ("A", "B", "C"):
        wb[name].cell(1, 1, value=name)
    wb.save(xlsx)
    wb.close()

    out = tmp_path / "out_xlsx"
    r = converter.convert_document(
        str(xlsx),
        str(out),
        output_format="markdown",
        page_start=1,
        page_end=2,
    )
    assert r["ok"] is True
    text = Path(r["output_path"]).read_text(encoding="utf-8")
    assert "## A" in text
    assert "## B" in text
    assert "## C" not in text


def test_xlsx_sheet_names(converter: DocumentConverter, tmp_path: Path) -> None:
    xlsx = tmp_path / "wb2.xlsx"
    wb = openpyxl.Workbook()
    wb.active.title = "One"
    wb.create_sheet("Two")
    wb["One"].cell(1, 1, value="alpha")
    wb["Two"].cell(1, 1, value="beta")
    wb.save(xlsx)
    wb.close()

    out = tmp_path / "out_xlsx2"
    r = converter.convert_document(
        str(xlsx),
        str(out),
        output_format="txt",
        sheet_names=["Two"],
    )
    assert r["ok"] is True
    text = Path(r["output_path"]).read_text(encoding="utf-8")
    assert "beta" in text
    assert "alpha" not in text


def test_docx_to_txt(converter: DocumentConverter, tmp_path: Path) -> None:
    from docx import Document as DocxDocument

    docx = tmp_path / "sample.docx"
    d = DocxDocument()
    d.add_paragraph("paragraph one")
    table = d.add_table(rows=1, cols=2)
    table.cell(0, 0).text = "c0"
    table.cell(0, 1).text = "c1"
    d.save(docx)

    out = tmp_path / "out_docx_txt"
    r = converter.convert_document(
        str(docx),
        str(out),
        output_format="txt",
    )
    assert r["ok"] is True
    text = Path(r["output_path"]).read_text(encoding="utf-8")
    assert "paragraph one" in text
    assert "c0" in text and "c1" in text
    assert str(r["output_path"]).endswith(".txt")


def test_convert_to_markdown_backward_compat(
    converter: DocumentConverter, tmp_path: Path
) -> None:
    import fitz

    pdf = tmp_path / "one.pdf"
    doc = fitz.open()
    doc.new_page()
    doc[0].insert_text((72, 72), "x")
    doc.save(pdf)
    doc.close()

    out = tmp_path / "out_md"
    r = converter.convert_to_markdown(str(pdf), str(out))
    assert r["ok"] is True
    assert r["markdown"] == r["output_path"]
    assert r["assets"] == r["images_dir"]
