"""
Unified profiler for image processing benchmark.
Profiles both CPU (cProfile) and memory (tracemalloc).
"""

import cProfile
import io
import os
import pstats
import sys
import tracemalloc

# Add odoo to path
sys.path.insert(0, "/Users/krrt7/Desktop/work/odoo_org/odoo")
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)

# Import benchmark module
sys.path.insert(0, "/Users/krrt7/Desktop/work/odoo_org/odoo/.codeflash")
from benchmark_image import (
    benchmark_base64_operations,
    benchmark_format_conversion,
    benchmark_resize_pil,
    benchmark_thumbnail_pil,
    create_test_image,
)


def profile_image_operations():
    """Profile image operations with CPU and memory tracking."""

    # Start memory profiling
    tracemalloc.start()

    # Start CPU profiling
    profiler = cProfile.Profile()
    profiler.enable()

    # Run benchmark operations
    print("Running profiled image operations...")

    # Create test images
    small_img = create_test_image(512, 512)
    medium_img = create_test_image(2048, 2048)

    # Run operations multiple times for better profiling data
    for _ in range(5):
        benchmark_resize_pil(medium_img, (512, 512))
        benchmark_thumbnail_pil(medium_img, (256, 256))
        benchmark_format_conversion(small_img)
        benchmark_base64_operations(medium_img)

    # Stop CPU profiling
    profiler.disable()

    # Get memory snapshot
    snapshot = tracemalloc.take_snapshot()

    # Print CPU profile
    print("\n" + "=" * 80)
    print("CPU PROFILE (top 40 by cumulative time)")
    print("=" * 80)
    s = io.StringIO()
    ps = pstats.Stats(profiler, stream=s)
    ps.strip_dirs()
    ps.sort_stats("cumulative")
    ps.print_stats(40)
    print(s.getvalue())

    print("\n" + "=" * 80)
    print("CPU PROFILE (top 40 by total time)")
    print("=" * 80)
    s = io.StringIO()
    ps = pstats.Stats(profiler, stream=s)
    ps.strip_dirs()
    ps.sort_stats("tottime")
    ps.print_stats(40)
    print(s.getvalue())

    # Print memory profile
    print("\n" + "=" * 80)
    print("MEMORY PROFILE (top 40 allocations)")
    print("=" * 80)
    top_stats = snapshot.statistics("lineno")
    for index, stat in enumerate(top_stats[:40], 1):
        print(f"{index:2}. {stat}")

    print("\n" + "=" * 80)
    print("MEMORY PROFILE (grouped by file)")
    print("=" * 80)
    top_stats = snapshot.statistics("filename")
    for index, stat in enumerate(top_stats[:30], 1):
        print(f"{index:2}. {stat}")

    # Save detailed profiles
    profiler.dump_stats(
        "/Users/krrt7/Desktop/work/odoo_org/odoo/.codeflash/cpu_profile.prof"
    )

    # Summary
    current, peak = tracemalloc.get_traced_memory()
    print("\n" + "=" * 80)
    print("MEMORY SUMMARY")
    print("=" * 80)
    print(f"Current memory: {current / 1024 / 1024:.1f} MiB")
    print(f"Peak memory: {peak / 1024 / 1024:.1f} MiB")

    tracemalloc.stop()

    # Save memory data
    with open(
        "/Users/krrt7/Desktop/work/odoo_org/odoo/.codeflash/memory_baseline.txt",
        "w",
    ) as f:
        f.write(f"Peak memory: {peak / 1024 / 1024:.1f} MiB\n")
        f.write(f"Current memory: {current / 1024 / 1024:.1f} MiB\n")

    return True


if __name__ == "__main__":
    success = profile_image_operations()
    sys.exit(0 if success else 1)
