"""docx → pdf：校验与可选 LibreOffice 集成。"""

from __future__ import annotations

from pathlib import Path

import pytest
from docx import Document

from aicd.tools.docx_to_pdf import (
    export_docx_to_pdf,
    find_soffice_executable,
    install_suggestions_docx_to_pdf,
)


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


def _minimal_docx(path: Path) -> None:
    d = Document()
    d.add_paragraph("aicd pdf test")
    d.save(path)


def test_export_rejects_non_docx(tmp_path: Path) -> None:
    f = tmp_path / "nope.txt"
    f.write_text("x", encoding="utf-8")
    r = export_docx_to_pdf(f, None, policy_check=_policy_ok)
    assert r["ok"] is False


def test_export_rejects_bad_pdf_suffix(tmp_path: Path) -> None:
    docx = tmp_path / "a.docx"
    _minimal_docx(docx)
    out = tmp_path / "out.xyz"
    r = export_docx_to_pdf(docx, out, policy_check=_policy_ok)
    assert r["ok"] is False


def test_export_libreoffice_when_available(tmp_path: Path) -> None:
    if find_soffice_executable() is None:
        pytest.skip("LibreOffice (soffice) not installed")
    docx = tmp_path / "lo.docx"
    _minimal_docx(docx)
    pdf = tmp_path / "custom_name.pdf"
    r = export_docx_to_pdf(docx, pdf, policy_check=_policy_ok, prefer="libreoffice")
    assert r["ok"] is True
    assert pdf.is_file() and pdf.stat().st_size > 0
    assert r.get("via") == "libreoffice"


def test_install_suggestions_nonempty() -> None:
    sug = install_suggestions_docx_to_pdf()
    assert isinstance(sug, list) and len(sug) >= 1
    assert all("title" in x for x in sug)


def test_failure_includes_ask_install_metadata(tmp_path: Path) -> None:
    if find_soffice_executable() is not None:
        pytest.skip("LibreOffice present")
    docx = tmp_path / "failmeta.docx"
    _minimal_docx(docx)
    r = export_docx_to_pdf(docx, tmp_path / "out.pdf", policy_check=_policy_ok)
    assert r["ok"] is False
    assert "install_suggestions" in r and isinstance(r["install_suggestions"], list)
    assert r.get("next_step_for_agent")


def test_default_pdf_next_to_docx(tmp_path: Path) -> None:
    if find_soffice_executable() is None:
        pytest.skip("LibreOffice (soffice) not installed")
    docx = tmp_path / "side.docx"
    _minimal_docx(docx)
    expected = tmp_path / "side.pdf"
    r = export_docx_to_pdf(docx, None, policy_check=_policy_ok, prefer="libreoffice")
    assert r["ok"] is True
    assert expected.is_file()
