"""Performance profiling for MCA SDK overhead analysis.

Profiles SDK hot paths to identify optimization opportunities.
Part of Story 6-9: Performance Testing (<50ms overhead).

FIX #7: Uses shared factory function to eliminate code duplication.

Usage:
    python tests/performance/profile_overhead.py

Output:
    tests/performance/results/overhead_profile.txt
"""

import cProfile
import pstats
import sys
import time
from io import StringIO
from pathlib import Path

# FIX #7: Import shared factory function
sys.path.insert(0, str(Path(__file__).parent.parent.parent))
from tests.performance.utils import create_benchmark_client


def profile_record_prediction_hot_paths():
    """Profile record_prediction() to identify hot paths.

    Returns:
        str: Profiling report text
    """
    print("Profiling record_prediction() hot paths...")

    profiler = cProfile.Profile()

    # FIX #7: Use shared factory function
    client = create_benchmark_client()

    # Profile 1000 prediction recordings
    profiler.enable()

    for i in range(1000):
        client.record_prediction(
            latency=0.1,
            model_version="v1.0",
            input_size=1024,
            output_size=512,
            prediction_id=f"pred-{i}",
        )

    profiler.disable()
    client.shutdown()

    # Generate report
    stream = StringIO()
    stats = pstats.Stats(profiler, stream=stream)
    stats.strip_dirs()
    stats.sort_stats("cumulative")

    stream.write("=" * 80 + "\n")
    stream.write("RECORD_PREDICTION() HOT PATH ANALYSIS\n")
    stream.write("=" * 80 + "\n\n")
    stream.write("Top 20 functions by cumulative time:\n")
    stream.write("-" * 80 + "\n")

    stats.print_stats(20)

    stream.write("\n" + "=" * 80 + "\n")
    stream.write("OPTIMIZATION OPPORTUNITIES\n")
    stream.write("=" * 80 + "\n\n")
    stream.write("Review functions with high cumulative time:\n")
    stream.write("- Attribute validation\n")
    stream.write("- Metric recording\n")
    stream.write("- OTel span creation\n")
    stream.write("- Serialization\n\n")

    return stream.getvalue()


def profile_trace_context_manager():
    """Profile client.trace() span creation overhead.

    Returns:
        str: Profiling report text
    """
    print("Profiling trace() context manager...")

    profiler = cProfile.Profile()

    # FIX #7: Use shared factory function
    client = create_benchmark_client()

    # Profile 1000 span creations
    profiler.enable()

    for i in range(1000):
        with client.trace(f"operation_{i}"):
            pass  # Empty span to measure pure overhead

    profiler.disable()
    client.shutdown()

    # Generate report
    stream = StringIO()
    stats = pstats.Stats(profiler, stream=stream)
    stats.strip_dirs()
    stats.sort_stats("cumulative")

    stream.write("\n" + "=" * 80 + "\n")
    stream.write("TRACE() CONTEXT MANAGER HOT PATH ANALYSIS\n")
    stream.write("=" * 80 + "\n\n")
    stream.write("Top 20 functions by cumulative time:\n")
    stream.write("-" * 80 + "\n")

    stats.print_stats(20)

    stream.write("\n" + "=" * 80 + "\n")
    stream.write("SPAN CREATION BOTTLENECKS\n")
    stream.write("=" * 80 + "\n\n")
    stream.write("Review OpenTelemetry span creation overhead:\n")
    stream.write("- Span initialization\n")
    stream.write("- Context propagation\n")
    stream.write("- Attribute attachment\n\n")

    return stream.getvalue()


def main():
    """Run all profiling and generate report."""
    print("=" * 80)
    print("MCA SDK Performance Profiling (Story 6-9)")
    print("=" * 80)
    print()

    # Ensure results directory exists
    results_dir = Path(__file__).parent / "results"
    results_dir.mkdir(exist_ok=True)
    output_file = results_dir / "overhead_profile.txt"

    # Profile record_prediction()
    report = profile_record_prediction_hot_paths()

    # Profile trace() context manager
    report += profile_trace_context_manager()

    # Write report
    with open(output_file, "w") as f:
        f.write(report)

    print(f"\n✅ Profiling report saved to: {output_file}")
    print(f"   File size: {output_file.stat().st_size} bytes")
    print()
    print("Next steps:")
    print("1. Review top 20 functions by cumulative time")
    print("2. Identify optimization opportunities")
    print("3. Run performance tests to validate current overhead")
    print(
        "   pytest tests/performance/test_performance.py::test_record_prediction_overhead_with_baseline_comparison -v"
    )


if __name__ == "__main__":
    main()
