"""
Unified profiler for Odoo test_orm performance tests.
Profiles both CPU (cProfile) and memory (tracemalloc) in a single run.
"""

import cProfile
import io
import pstats
import sys
import tracemalloc
import unittest

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


def profile_tests():
    """Run test_performance with CPU and memory profiling."""

    # Start memory profiling
    tracemalloc.start()

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

    # Discover and run tests
    loader = unittest.TestLoader()
    suite = loader.discover(
        start_dir="/Users/krrt7/Desktop/work/odoo_org/odoo/odoo/addons/test_orm/tests",
        pattern="test_performance.py",
    )

    runner = unittest.TextTestRunner(verbosity=2)
    result = runner.run(suite)

    # Stop CPU profiling
    profiler.disable()

    # Get memory snapshot
    snapshot = tracemalloc.take_snapshot()

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

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

    # Print memory profile
    print("\n" + "=" * 80)
    print("MEMORY PROFILE (top 30 allocations)")
    print("=" * 80)
    top_stats = snapshot.statistics("lineno")
    for index, stat in enumerate(top_stats[:30], 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[:20], 1):
        print(f"{index:2}. {stat}")

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

    # Summary
    print("\n" + "=" * 80)
    print("SUMMARY")
    print("=" * 80)
    print(f"Tests run: {result.testsRun}")
    print(f"Failures: {len(result.failures)}")
    print(f"Errors: {len(result.errors)}")

    current, peak = tracemalloc.get_traced_memory()
    print(f"Current memory: {current / 1024 / 1024:.1f} MiB")
    print(f"Peak memory: {peak / 1024 / 1024:.1f} MiB")

    tracemalloc.stop()

    return result.wasSuccessful()


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