"""Tests for export functions."""
import pytest
import tempfile
from pathlib import Path
from openslides import Brand, export, export_async, export_pdf, base_html


# Simple test slide
def make_test_slide(brand: Brand, text: str = "Test") -> str:
    return f'''{base_html(brand)}
<body style="background:{brand.background}; display:flex; align-items:center; justify-content:center;">
    <h1 style="font-size:72px; color:{brand.text};">{text}</h1>
</body></html>'''


class TestExport:
    """Test export function."""

    def test_export_creates_directory(self):
        """export creates output directory if needed."""
        brand = Brand()
        slides = [make_test_slide(brand)]

        with tempfile.TemporaryDirectory() as tmpdir:
            output_dir = Path(tmpdir) / "new_subdir"
            assert not output_dir.exists()

            paths = export(slides, str(output_dir))

            assert output_dir.exists()
            assert len(paths) == 1

    def test_export_creates_png_files(self):
        """export creates PNG files."""
        brand = Brand()
        slides = [make_test_slide(brand, "Slide 1"), make_test_slide(brand, "Slide 2")]

        with tempfile.TemporaryDirectory() as tmpdir:
            paths = export(slides, tmpdir)

            assert len(paths) == 2
            assert all(p.endswith(".png") for p in paths)
            assert all(Path(p).exists() for p in paths)

    def test_export_creates_html_files(self):
        """export also saves HTML source files."""
        brand = Brand()
        slides = [make_test_slide(brand)]

        with tempfile.TemporaryDirectory() as tmpdir:
            export(slides, tmpdir)

            html_path = Path(tmpdir) / "slide-01.html"
            assert html_path.exists()
            assert "<!DOCTYPE html>" in html_path.read_text()

    def test_export_naming_convention(self):
        """export uses slide-01, slide-02, etc naming."""
        brand = Brand()
        slides = [make_test_slide(brand) for _ in range(3)]

        with tempfile.TemporaryDirectory() as tmpdir:
            paths = export(slides, tmpdir)

            assert "slide-01.png" in paths[0]
            assert "slide-02.png" in paths[1]
            assert "slide-03.png" in paths[2]

    def test_export_custom_dimensions(self):
        """export respects width/height parameters."""
        brand = Brand()
        slides = [make_test_slide(brand)]

        with tempfile.TemporaryDirectory() as tmpdir:
            # Use smaller dimensions for faster test
            paths = export(slides, tmpdir, width=800, height=600)

            assert len(paths) == 1
            # PNG was created (dimensions are in the file but we just check it exists)
            assert Path(paths[0]).stat().st_size > 0


class TestExportPdf:
    """Test PDF export functionality."""

    def test_export_pdf_creates_pdf_files(self):
        """export with format='pdf' creates PDF files."""
        brand = Brand()
        slides = [make_test_slide(brand)]

        with tempfile.TemporaryDirectory() as tmpdir:
            paths = export(slides, tmpdir, format="pdf")

            assert len(paths) == 1
            assert paths[0].endswith(".pdf")
            assert Path(paths[0]).exists()
            # PDF files start with %PDF
            with open(paths[0], "rb") as f:
                assert f.read(4) == b"%PDF"

    def test_export_pdf_convenience_function(self):
        """export_pdf convenience function works."""
        brand = Brand()
        slides = [make_test_slide(brand)]

        with tempfile.TemporaryDirectory() as tmpdir:
            paths = export_pdf(slides, tmpdir)

            assert len(paths) == 1
            assert paths[0].endswith(".pdf")

    def test_export_invalid_format_raises(self):
        """export with invalid format raises ValueError."""
        brand = Brand()
        slides = [make_test_slide(brand)]

        with tempfile.TemporaryDirectory() as tmpdir:
            with pytest.raises(ValueError, match="format must be"):
                export(slides, tmpdir, format="jpeg")


@pytest.mark.asyncio
class TestExportAsync:
    """Test export_async function."""

    async def test_export_async_works(self):
        """export_async creates files."""
        brand = Brand()
        slides = [make_test_slide(brand)]

        with tempfile.TemporaryDirectory() as tmpdir:
            paths = await export_async(slides, tmpdir)

            assert len(paths) == 1
            assert Path(paths[0]).exists()
