"""Tests para compress_pdf_ghostscript."""
from __future__ import annotations

import shutil
import tempfile
from pathlib import Path

import pytest


def _make_simple_pdf(path: Path) -> None:
    """Create a minimal valid PDF using fpdf2."""
    try:
        from fpdf import FPDF
        pdf = FPDF()
        pdf.add_page()
        pdf.set_font("Helvetica", size=12)
        pdf.cell(200, 10, text="Test PDF for ghostscript compression", ln=True)
        pdf.output(str(path))
    except ImportError:
        # Fallback: write a minimal PDF manually
        content = (
            b"%PDF-1.4\n"
            b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n"
            b"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n"
            b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>\nendobj\n"
            b"xref\n0 4\n0000000000 65535 f \n0000000009 00000 n \n"
            b"0000000068 00000 n \n0000000125 00000 n \n"
            b"trailer\n<< /Size 4 /Root 1 0 R >>\nstartxref\n210\n%%EOF\n"
        )
        path.write_bytes(content)


def test_crea_pdf_temporal_y_comprime_retorna_bool_sin_excepcion():
    """crea pdf temporal y comprime - retorna bool sin excepcion"""
    import sys
    sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
    from infra.compress_pdf_ghostscript import compress_pdf_ghostscript

    with tempfile.TemporaryDirectory() as tmpdir:
        pdf_path = Path(tmpdir) / "test.pdf"
        _make_simple_pdf(pdf_path)
        assert pdf_path.exists()
        result = compress_pdf_ghostscript(pdf_path)
        assert isinstance(result, bool)
        # File must still exist regardless of whether compression happened
        assert pdf_path.exists()


def test_retorna_False_cuando_gs_no_esta_disponible(monkeypatch):
    """retorna False cuando gs no esta disponible"""
    import sys
    sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
    from infra.compress_pdf_ghostscript import compress_pdf_ghostscript

    monkeypatch.setattr("shutil.which", lambda x: None)

    with tempfile.TemporaryDirectory() as tmpdir:
        pdf_path = Path(tmpdir) / "test.pdf"
        _make_simple_pdf(pdf_path)
        result = compress_pdf_ghostscript(pdf_path)
        assert result is False
