"""Tests for src/core/docx.py."""

import subprocess
from pathlib import Path
from unittest.mock import patch, MagicMock

import pytest
from docx import Document

from src.core.docx import convert_to_pdf


def _make_docx(path: Path) -> Path:
    """Create a minimal valid DOCX file at the given path."""
    doc = Document()
    doc.add_paragraph("Hello from PageFuse test.")
    doc.save(str(path))
    return path


# ---------------------------------------------------------------------------
# Error paths (no LibreOffice required)
# ---------------------------------------------------------------------------

def test_libreoffice_not_installed(tmp_path):
    docx_path = str(_make_docx(tmp_path / "doc.docx"))
    with patch("subprocess.run", side_effect=FileNotFoundError):
        with pytest.raises(RuntimeError, match="LibreOffice is not installed"):
            convert_to_pdf(docx_path, str(tmp_path))


def test_libreoffice_nonzero_exit(tmp_path):
    docx_path = str(_make_docx(tmp_path / "doc.docx"))
    mock_result = MagicMock()
    mock_result.returncode = 1
    mock_result.stderr = "some libreoffice error"
    with patch("subprocess.run", return_value=mock_result):
        with pytest.raises(RuntimeError, match="LibreOffice failed to convert"):
            convert_to_pdf(docx_path, str(tmp_path))


def test_output_pdf_missing_after_conversion(tmp_path):
    """Returncode 0 but the expected PDF file was not created."""
    docx_path = str(_make_docx(tmp_path / "doc.docx"))
    mock_result = MagicMock()
    mock_result.returncode = 0
    with patch("subprocess.run", return_value=mock_result):
        with pytest.raises(FileNotFoundError, match="output not found"):
            convert_to_pdf(docx_path, str(tmp_path))


# ---------------------------------------------------------------------------
# Happy path (requires LibreOffice)
# ---------------------------------------------------------------------------

@pytest.mark.skipif(
    subprocess.run(["which", "libreoffice"], capture_output=True).returncode != 0,
    reason="LibreOffice not available",
)
def test_convert_docx_to_pdf(tmp_path):
    docx_path = str(_make_docx(tmp_path / "doc.docx"))
    pdf_path = convert_to_pdf(docx_path, str(tmp_path))
    assert Path(pdf_path).exists()
    assert pdf_path.endswith(".pdf")
    assert Path(pdf_path).stat().st_size > 0
