"""Performance benchmarks for img2pdf functionality."""

import tempfile
from pathlib import Path

import pytest
from PIL import Image

from pytola.office.img2pdf.img2pdf import ImageToPDFRunner


@pytest.mark.benchmark(group="img2pdf-performance")
def test_benchmark_large_image_conversion(benchmark):
    """Benchmark conversion of a large image."""
    with tempfile.TemporaryDirectory() as temp_dir:
        temp_path = Path(temp_dir)

        # Create a large image
        large_img = temp_path / "large_image.jpg"
        img = Image.new("RGB", (2000, 2000), color="red")
        img.save(large_img, "JPEG")

        def run_conversion():
            runner = ImageToPDFRunner(root_dir=temp_path, dpi=72, normalize=False)
            return runner._convert(large_img, normalize=False)

        result = benchmark(run_conversion)
        assert result is not None


@pytest.mark.benchmark(group="img2pdf-performance")
def test_benchmark_multiple_image_processing(benchmark):
    """Benchmark processing multiple images."""
    with tempfile.TemporaryDirectory() as temp_dir:
        temp_path = Path(temp_dir)

        # Create multiple images
        for i in range(5):
            img_path = temp_path / f"image_{i}.jpg"
            img = Image.new("RGB", (500, 500), color=(i * 50, i * 30, i * 20))
            img.save(img_path, "JPEG")

        def run_processing():
            runner = ImageToPDFRunner(root_dir=temp_path, dpi=72, normalize=False)
            return runner.image_files

        result = benchmark(run_processing)
        assert len(result) == 5


@pytest.mark.benchmark(group="img2pdf-performance")
def test_benchmark_image_scaling_operations(benchmark):
    """Benchmark image scaling operations."""
    with tempfile.TemporaryDirectory() as temp_dir:
        temp_path = Path(temp_dir)

        # Create an image
        img_path = temp_path / "scale_test.png"
        img = Image.new("RGB", (1000, 1000), color="blue")
        img.save(img_path, "PNG")

        runner = ImageToPDFRunner(root_dir=temp_path, dpi=72, normalize=True)

        def run_scaling():
            # Open image, perform scaling, and close it to avoid file locks
            with Image.open(img_path) as pil_img:
                return runner._auto_scale_image(pil_img)

        result = benchmark(run_scaling)
        assert result is not None


@pytest.mark.benchmark(group="img2pdf-performance")
def test_benchmark_page_size_calculations(benchmark):
    """Benchmark page size calculations."""
    with tempfile.TemporaryDirectory() as temp_dir:
        temp_path = Path(temp_dir)
        runner = ImageToPDFRunner(root_dir=temp_path, dpi=300, normalize=False)

        def run_page_size_access():
            return runner.page_size

        result = benchmark(run_page_size_access)
        assert result == (int(8.27 * 300), int(11.69 * 300))


if __name__ == "__main__":
    pytest.main([__file__])
