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

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

import pytest
from pptx import Presentation

from src.core.pptx import convert_to_pdf


def _make_pptx(path: Path) -> Path:
    """Create a minimal valid PPTX file at the given path."""
    prs = Presentation()
    slide_layout = prs.slide_layouts[0]  # title slide
    slide = prs.slides.add_slide(slide_layout)
    slide.shapes.title.text = "PageFuse Test Slide"
    prs.save(str(path))
    return path


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

def test_libreoffice_not_installed(tmp_path):
    pptx_path = str(_make_pptx(tmp_path / "deck.pptx"))
    with patch("subprocess.run", side_effect=FileNotFoundError):
        with pytest.raises(RuntimeError, match="LibreOffice is not installed"):
            convert_to_pdf(pptx_path, str(tmp_path))


def test_libreoffice_nonzero_exit(tmp_path):
    pptx_path = str(_make_pptx(tmp_path / "deck.pptx"))
    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(pptx_path, str(tmp_path))


def test_output_pdf_missing_after_conversion(tmp_path):
    """Returncode 0 but the expected PDF file was not created."""
    pptx_path = str(_make_pptx(tmp_path / "deck.pptx"))
    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(pptx_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_pptx_to_pdf(tmp_path):
    pptx_path = str(_make_pptx(tmp_path / "deck.pptx"))
    pdf_path = convert_to_pdf(pptx_path, str(tmp_path))
    assert Path(pdf_path).exists()
    assert pdf_path.endswith(".pdf")
    assert Path(pdf_path).stat().st_size > 0
