from pathlib import Path

from pymultirole_plugins.v1.schema import Document, DocumentList
from starlette.datastructures import Headers, UploadFile

from pyconverters_pyword.pyword import PyWordConverter, PyWordParameters

TESTDIR = Path(__file__).parent
CONF_DOCX = TESTDIR / "data/CONFERENCE DE REDACTION QUOTIDIENNE.docx"
LLM_DOCX = TESTDIR / "data/PC_Kairntech_LLM_v1.docx"


def _make_upload(path: Path, fin) -> UploadFile:
    return UploadFile(
        file=fin,
        filename=path.name,
        headers=Headers({"content-type": "application/octet-stream"}),
    )


# @pytest.mark.skip(reason="Not a test")
def test_pyword():
    converter = PyWordConverter()
    parameters = PyWordParameters(include_image_base64_as_altTexts=True)
    source = CONF_DOCX
    with source.open("rb") as fin:
        docs: list[Document] = converter.convert(_make_upload(source, fin), parameters)
        assert len(docs) == 1
        assert docs[0].identifier
        assert docs[0].text
    md_file = source.with_suffix(".md")
    dl = DocumentList(root=docs)
    with md_file.open("w") as fout:
        fout.write(docs[0].text)
    json_file = source.with_suffix(".md.json")
    dl = DocumentList(root=docs)
    with json_file.open("w") as fout:
        print(dl.model_dump_json(exclude_none=True, exclude_unset=True, indent=2), file=fout)


def test_pyword_identifier_is_filename():
    converter = PyWordConverter()
    parameters = PyWordParameters()
    source = CONF_DOCX
    with source.open("rb") as fin:
        docs = converter.convert(_make_upload(source, fin), parameters)
    assert docs[0].identifier == source.name


def test_pyword_image_as_altTexts():
    converter = PyWordConverter()
    parameters = PyWordParameters(include_image_base64_as_altTexts=True)
    source = LLM_DOCX
    with source.open("rb") as fin:
        docs = converter.convert(_make_upload(source, fin), parameters)
    assert len(docs) == 1
    assert docs[0].text
    # If the document contains images, altTexts should be populated with valid mime-types
    if docs[0].altTexts:
        for alt in docs[0].altTexts:
            assert alt.properties.get("mime-type", "").startswith("image/")


def test_pyword_image_as_links():
    converter = PyWordConverter()
    parameters = PyWordParameters(include_image_base64_as_links=True)
    source = LLM_DOCX
    with source.open("rb") as fin:
        docs = converter.convert(_make_upload(source, fin), parameters)
    assert len(docs) == 1
    assert docs[0].text
    # If the document contains images, they should be embedded as data: URIs
    if "data:image" in docs[0].text:
        assert "base64," in docs[0].text
