"""
Benchmark for Odoo image processing utilities - Optimized version 1.
Optimization: Use numpy array for efficient image creation instead of per-pixel operations.
"""

import base64
import io
import os
import sys
import timeit

import numpy as np
from PIL import Image

# Add odoo to path
sys.path.insert(0, "/Users/krrt7/Desktop/work/odoo_org/odoo")

# Activating venv programmatically by modifying path
venv_site_packages = (
    "/Users/krrt7/Desktop/work/odoo_org/odoo/venv/lib/python3.14/site-packages"
)
if os.path.exists(venv_site_packages):
    sys.path.insert(0, venv_site_packages)

try:
    from odoo.tools import image
except ImportError as e:
    print(f"Failed to import odoo.tools.image: {e}")
    print("This benchmark will run PIL operations directly.")
    image = None


def create_test_image(width=2048, height=2048):
    """Create a test image in memory using numpy for efficiency."""
    # Create array with red background (RGB)
    arr = np.full((height, width, 3), [255, 0, 0], dtype=np.uint8)

    # Add green pixels at intervals - use numpy slicing instead of loops
    arr[::100, ::100] = [0, 255, 0]

    # Convert numpy array to PIL Image
    img = Image.fromarray(arr, "RGB")

    buffer = io.BytesIO()
    img.save(buffer, format="PNG")
    return buffer.getvalue()


def benchmark_resize_pil(image_data, target_size=(512, 512)):
    """Benchmark PIL resize operation."""
    img = Image.open(io.BytesIO(image_data))
    img_resized = img.resize(target_size, Image.Resampling.LANCZOS)
    buffer = io.BytesIO()
    img_resized.save(buffer, format="PNG")
    return buffer.getvalue()


def benchmark_thumbnail_pil(image_data, max_size=(256, 256)):
    """Benchmark PIL thumbnail operation."""
    img = Image.open(io.BytesIO(image_data))
    img.thumbnail(max_size, Image.Resampling.LANCZOS)
    buffer = io.BytesIO()
    img.save(buffer, format="PNG")
    return buffer.getvalue()


def benchmark_format_conversion(image_data):
    """Benchmark format conversion (PNG -> JPEG -> PNG)."""
    img = Image.open(io.BytesIO(image_data))

    # Convert to JPEG
    buffer_jpeg = io.BytesIO()
    img_rgb = img.convert("RGB")
    img_rgb.save(buffer_jpeg, format="JPEG", quality=85)

    # Convert back to PNG
    img2 = Image.open(io.BytesIO(buffer_jpeg.getvalue()))
    buffer_png = io.BytesIO()
    img2.save(buffer_png, format="PNG")

    return buffer_png.getvalue()


def benchmark_base64_operations(image_data):
    """Benchmark base64 encoding/decoding."""
    encoded = base64.b64encode(image_data)
    decoded = base64.b64decode(encoded)
    return decoded


def run_benchmarks():
    """Run all image benchmarks."""
    print("=" * 80)
    print("Image Processing Benchmark - Optimized")
    print("=" * 80)

    # Create test images of different sizes
    test_sizes = [
        (512, 512, "Small (512x512)"),
        (2048, 2048, "Medium (2048x2048)"),
        (4096, 4096, "Large (4096x4096)"),
    ]

    results = []

    for width, height, label in test_sizes:
        print(f"\n{label}:")
        print("-" * 40)

        image_data = create_test_image(width, height)
        size_mb = len(image_data) / 1024 / 1024
        print(f"Image size: {size_mb:.2f} MB")

        # Benchmark resize
        time_resize = (
            timeit.timeit(
                lambda: benchmark_resize_pil(image_data, (512, 512)), number=10
            )
            / 10
        )
        print(f"Resize to 512x512: {time_resize * 1000:.2f} ms")

        # Benchmark thumbnail
        time_thumbnail = (
            timeit.timeit(
                lambda: benchmark_thumbnail_pil(image_data, (256, 256)),
                number=10,
            )
            / 10
        )
        print(f"Thumbnail to 256x256: {time_thumbnail * 1000:.2f} ms")

        # Benchmark format conversion
        time_format = (
            timeit.timeit(
                lambda: benchmark_format_conversion(image_data), number=5
            )
            / 5
        )
        print(
            f"Format conversion (PNG->JPEG->PNG): {time_format * 1000:.2f} ms"
        )

        # Benchmark base64
        time_base64 = (
            timeit.timeit(
                lambda: benchmark_base64_operations(image_data), number=100
            )
            / 100
        )
        print(f"Base64 encode/decode: {time_base64 * 1000:.2f} ms")

        results.append(
            {
                "size": label,
                "image_mb": size_mb,
                "resize_ms": time_resize * 1000,
                "thumbnail_ms": time_thumbnail * 1000,
                "format_ms": time_format * 1000,
                "base64_ms": time_base64 * 1000,
            }
        )

    # Summary
    print("\n" + "=" * 80)
    print("SUMMARY")
    print("=" * 80)
    for r in results:
        print(f"\n{r['size']} ({r['image_mb']:.2f} MB):")
        print(
            f"  Total processing time: {r['resize_ms'] + r['thumbnail_ms'] + r['format_ms']:.2f} ms"
        )


if __name__ == "__main__":
    run_benchmarks()
