# Performance validation script for vendor bridge conversion logic
# Validates AC requirement: "Conversion logic <50ms per polling cycle"

import time
import statistics
import json
from pathlib import Path

# Add parent directory to path for imports
import sys
sys.path.insert(0, str(Path(__file__).parent.parent.parent))

from mca_sdk.integrations.bridge import VendorBridge


class PerformanceTestBridge(VendorBridge):
    """Bridge implementation for performance testing."""

    def __init__(self, *args, **kwargs):
        self._cumulative_predictions = 0
        self._cumulative_errors = 0
        super().__init__(*args, **kwargs)

    def fetch_metrics(self):
        """Mock fetch - not used in performance test."""
        return {
            "metrics": {
                "predictions_delta": 42,
                "errors_delta": 1,
                "accuracy": 0.95,
                "f1_score": 0.88,
                "latency_p50": 25.3,
                "latency_p90": 45.7,
                "latency_p99": 125.5,
                "memory_usage_mb": 256,
                "cpu_usage_percent": 15.3,
            }
        }

    def transform_metrics(self, data):
        """Transform with delta-to-cumulative conversion."""
        metrics = data.get("metrics", {})

        # Extract delta values
        predictions_delta = metrics.get("predictions_delta", 0)
        errors_delta = metrics.get("errors_delta", 0)

        # Thread-safe cumulative conversion
        with self._lock:
            self._cumulative_predictions += predictions_delta
            self._cumulative_errors += errors_delta

            return {
                "vendor.predictions_total": self._cumulative_predictions,
                "vendor.errors_total": self._cumulative_errors,
                "vendor.accuracy_ratio": metrics.get("accuracy", 0),
                "vendor.fscore_ratio": metrics.get("f1_score", 0),
                "vendor.latency_seconds": metrics.get("latency_p99", 0) / 1000.0,
            }


def run_performance_validation():
    """Run comprehensive performance validation."""
    print("=" * 70)
    print("Vendor Bridge Performance Validation")
    print("=" * 70)
    print()
    print("AC Requirement: Conversion logic <50ms per polling cycle")
    print("(From Dev Notes: Story 5-4)")
    print()

    # Initialize bridge (mock client to avoid real SDK calls)
    try:
        from unittest.mock import MagicMock, patch

        with patch("mca_sdk.integrations.bridge.MCAClient") as mock_client_class:
            mock_client_class.return_value = MagicMock()

            bridge = PerformanceTestBridge(
                service_name="performance-test",
                vendor_name="test-vendor",
                endpoint="http://localhost:8080",
            )

            # Test data (realistic vendor JSON)
            test_data = bridge.fetch_metrics()

            # Warm-up runs (JIT compilation, cache warming)
            print("Running warm-up iterations...")
            for _ in range(100):
                bridge.transform_metrics(test_data)

            # Performance measurement
            print("Running performance test (1000 iterations)...\n")
            times_ms = []

            for i in range(1000):
                start = time.perf_counter()
                bridge.transform_metrics(test_data)
                elapsed = (time.perf_counter() - start) * 1000  # Convert to ms
                times_ms.append(elapsed)

            # Calculate statistics
            mean_time = statistics.mean(times_ms)
            median_time = statistics.median(times_ms)
            stdev_time = statistics.stdev(times_ms)
            min_time = min(times_ms)
            max_time = max(times_ms)
            p95_time = sorted(times_ms)[int(len(times_ms) * 0.95)]
            p99_time = sorted(times_ms)[int(len(times_ms) * 0.99)]

            # Display results
            print("-" * 70)
            print("PERFORMANCE TEST RESULTS")
            print("-" * 70)
            print("Total Iterations:     1000")
            print(f"Mean Time:            {mean_time:.4f} ms")
            print(f"Median Time:          {median_time:.4f} ms")
            print(f"Std Deviation:        {stdev_time:.4f} ms")
            print(f"Min Time:             {min_time:.4f} ms")
            print(f"Max Time:             {max_time:.4f} ms")
            print(f"95th Percentile:      {p95_time:.4f} ms")
            print(f"99th Percentile:      {p99_time:.4f} ms")
            print()

            # Validation against AC requirement
            print("-" * 70)
            print("ACCEPTANCE CRITERIA VALIDATION")
            print("-" * 70)
            print("Requirement:          <50.0 ms per conversion")
            print(f"Mean Time:            {mean_time:.4f} ms")
            print(f"99th Percentile:      {p99_time:.4f} ms")
            print()

            # Determine pass/fail
            mean_pass = mean_time < 50.0
            p99_pass = p99_time < 50.0
            all_pass = all(t < 50.0 for t in times_ms)

            print(f"Mean < 50ms:          {'✅ PASS' if mean_pass else '❌ FAIL'}")
            print(f"P99 < 50ms:           {'✅ PASS' if p99_pass else '❌ FAIL'}")
            print(f"All iterations <50ms: {'✅ PASS' if all_pass else '❌ FAIL'}")
            print()

            if mean_pass and p99_pass:
                print("🎉 OVERALL RESULT: ✅ PASS")
                print()
                print("Conversion performance meets AC requirement (<50ms).")
                margin = 50.0 - p99_time
                print(f"Performance margin: {margin:.4f}ms ({margin/50.0*100:.1f}% under limit)")
            else:
                print("⚠️  OVERALL RESULT: ❌ FAIL")
                print()
                print("Conversion performance exceeds AC requirement.")
                if not mean_pass:
                    print(f"  Mean time {mean_time:.4f}ms exceeds 50ms limit")
                if not p99_pass:
                    print(f"  P99 time {p99_time:.4f}ms exceeds 50ms limit")

            print()
            print("-" * 70)

            # Save results to file
            results = {
                "test_date": time.strftime("%Y-%m-%d %H:%M:%S"),
                "iterations": 1000,
                "requirement_ms": 50.0,
                "statistics": {
                    "mean_ms": mean_time,
                    "median_ms": median_time,
                    "stdev_ms": stdev_time,
                    "min_ms": min_time,
                    "max_ms": max_time,
                    "p95_ms": p95_time,
                    "p99_ms": p99_time,
                },
                "validation": {
                    "mean_pass": mean_pass,
                    "p99_pass": p99_pass,
                    "all_iterations_pass": all_pass,
                    "overall_pass": mean_pass and p99_pass,
                },
            }

            output_file = Path(__file__).parent / "performance_results.json"
            with open(output_file, "w") as f:
                json.dump(results, f, indent=2)

            print(f"Results saved to: {output_file}")
            print()

            # Return exit code based on pass/fail
            return 0 if (mean_pass and p99_pass) else 1

    except Exception as e:
        print(f"\n❌ Error during performance test: {e}")
        import traceback
        traceback.print_exc()
        return 2


if __name__ == "__main__":
    exit_code = run_performance_validation()
    sys.exit(exit_code)
