#!/usr/bin/env python3
"""
Performance Test Script
Tests SSR response times and API endpoint performance
"""

import time
import requests
import statistics
import json
from typing import Dict, List, Tuple

# Test configuration
BASE_URL = "http://localhost:10000"
NUM_ITERATIONS = 10
TIMEOUT = 10

def measure_response_time(url: str, iterations: int = NUM_ITERATIONS) -> Tuple[List[float], bool]:
    """Measure response time for a URL over multiple iterations"""
    times = []
    success = True

    for i in range(iterations):
        try:
            start = time.time()
            response = requests.get(url, timeout=TIMEOUT)
            end = time.time()

            if response.status_code != 200:
                print(f"  Warning: {url} returned status {response.status_code}")
                success = False

            times.append((end - start) * 1000)  # Convert to ms
            time.sleep(0.1)  # Small delay between requests
        except Exception as e:
            print(f"  Error testing {url}: {e}")
            success = False

    return times, success

def print_stats(name: str, times: List[float]):
    """Print statistics for response times"""
    if not times:
        print(f"\n{name}: No data")
        return

    avg = statistics.mean(times)
    median = statistics.median(times)
    min_time = min(times)
    max_time = max(times)

    # Performance thresholds
    status = "OK" if avg < 200 else "WARN" if avg < 500 else "SLOW"

    print(f"\n{name}:")
    print(f"  Average:  {avg:.2f}ms [{status}]")
    print(f"  Median:   {median:.2f}ms")
    print(f"  Min:      {min_time:.2f}ms")
    print(f"  Max:      {max_time:.2f}ms")

    if len(times) > 1:
        stddev = statistics.stdev(times)
        print(f"  Std Dev:  {stddev:.2f}ms")

def main():
    print("=" * 60)
    print("PERFORMANCE TEST REPORT")
    print("=" * 60)
    print(f"Base URL: {BASE_URL}")
    print(f"Iterations per endpoint: {NUM_ITERATIONS}")
    print()

    # Define test endpoints
    test_pages = {
        "Homepage": "/",
        "Case Studies": "/case-studies",
        "Contact": "/contact",
        "About": "/about",
    }

    test_apis = {
        "Health Check": "/api/health.json",
        "Sitemap": "/api/sitemap.xml",
    }

    all_passed = True
    results = {}

    # Test pages
    print("\n" + "=" * 60)
    print("TESTING SSR PAGES")
    print("=" * 60)

    for name, path in test_pages.items():
        url = f"{BASE_URL}{path}"
        print(f"\nTesting {name} ({url})...")
        times, success = measure_response_time(url)
        print_stats(name, times)
        results[name] = times
        all_passed = all_passed and success

    # Test API endpoints
    print("\n\n" + "=" * 60)
    print("TESTING API ENDPOINTS")
    print("=" * 60)

    for name, path in test_apis.items():
        url = f"{BASE_URL}{path}"
        print(f"\nTesting {name} ({url})...")
        times, success = measure_response_time(url)
        print_stats(name, times)
        results[name] = times
        all_passed = all_passed and success

    # Verify domain in sitemap
    print("\n\n" + "=" * 60)
    print("DOMAIN VERIFICATION")
    print("=" * 60)

    try:
        response = requests.get(f"{BASE_URL}/api/sitemap.xml", timeout=TIMEOUT)
        if "workroot.in" in response.text:
            print("\nOK: Sitemap contains 'workroot.in'")
        else:
            print("\nWARN: Sitemap does not contain 'workroot.in'")
            all_passed = False

        if "workroot.com" in response.text:
            print("ERROR: Sitemap still contains old domain 'workroot.com'")
            all_passed = False
    except Exception as e:
        print(f"\nError checking sitemap: {e}")
        all_passed = False

    # Overall summary
    print("\n\n" + "=" * 60)
    print("PERFORMANCE SUMMARY")
    print("=" * 60)

    # Calculate average response time across all endpoints
    all_times = []
    for times in results.values():
        all_times.extend(times)

    if all_times:
        overall_avg = statistics.mean(all_times)
        print(f"\nOverall Average Response Time: {overall_avg:.2f}ms")

        if overall_avg < 200:
            print("Performance: EXCELLENT (< 200ms)")
        elif overall_avg < 500:
            print("Performance: GOOD (< 500ms)")
        else:
            print("Performance: NEEDS IMPROVEMENT (>= 500ms)")

    # Recommendations
    print("\n" + "=" * 60)
    print("RECOMMENDATIONS")
    print("=" * 60)

    slow_endpoints = {name: statistics.mean(times)
                      for name, times in results.items()
                      if times and statistics.mean(times) > 500}

    if slow_endpoints:
        print("\nSlow endpoints detected (>500ms):")
        for name, avg_time in slow_endpoints.items():
            print(f"  - {name}: {avg_time:.2f}ms")
        print("\nConsider:")
        print("  - Implementing caching")
        print("  - Optimizing SSR hydration")
        print("  - Reducing bundle size")
    else:
        print("\nAll endpoints performing well! No immediate optimizations needed.")

    print("\n" + "=" * 60)

    if all_passed:
        print("RESULT: PASS")
        print("=" * 60)
        return 0
    else:
        print("RESULT: ISSUES DETECTED")
        print("=" * 60)
        return 1

if __name__ == "__main__":
    exit(main())
