#!/usr/bin/env python3
"""Production smoke tests for Fly.io deployment."""

import requests
import json
from datetime import datetime

BASE_URL = "https://rateright-au.fly.dev"

def test_endpoints():
    """Test all key endpoints."""
    results = []
    endpoints = [
        ("/", "GET", "Home page"),
        ("/login", "GET", "Login page"),
        ("/workers", "GET", "Workers page"),
        ("/api/workers", "GET", "Workers API"),
        ("/jobs", "GET", "Jobs page"),
        ("/contracts", "GET", "Contracts page"),
        ("/messages", "GET", "Messages page"),
        ("/_health", "GET", "Health check"),
        ("/_ready", "GET", "Ready check"),
    ]
    
    print(f"Running smoke tests on {BASE_URL}")
    print("=" * 60)
    
    for path, method, description in endpoints:
        url = f"{BASE_URL}{path}"
        try:
            if method == "GET":
                response = requests.get(url, timeout=10, allow_redirects=False)
            
            status = response.status_code
            
            # For auth-protected pages, 302 redirect to login is OK
            if status == 302 and path not in ["/_health", "/_ready", "/", "/login"]:
                status_msg = "302 (Auth redirect - OK)"
                success = True
            elif status < 500:
                status_msg = f"{status} (OK)"
                success = True
            else:
                status_msg = f"{status} (ERROR)"
                success = False
            
            result = {
                "endpoint": path,
                "status": status,
                "success": success,
                "description": description
            }
            results.append(result)
            
            icon = "✅" if success else "❌"
            print(f"{icon} {method} {path}: {status_msg} - {description}")
            
        except Exception as e:
            result = {
                "endpoint": path,
                "status": "ERROR",
                "success": False,
                "description": description,
                "error": str(e)
            }
            results.append(result)
            print(f"❌ {method} {path}: ERROR - {e}")
    
    print("=" * 60)
    
    # Summary
    success_count = sum(1 for r in results if r["success"])
    total_count = len(results)
    
    print(f"\nSummary: {success_count}/{total_count} endpoints passed")
    
    # Check for any 5xx errors
    errors_5xx = [r for r in results if isinstance(r["status"], int) and r["status"] >= 500]
    
    if errors_5xx:
        print("\n⚠️  WARNING: Found 5xx errors:")
        for err in errors_5xx:
            print(f"  - {err['endpoint']}: {err['status']}")
        return False
    else:
        print("\n✅ No 5xx errors found!")
        return True

def save_results(results):
    """Save test results to evidence file."""
    timestamp = datetime.now().isoformat()
    
    with open("evidence/fly/03_smoke.txt", "w", encoding="utf-8") as f:
        f.write(f"# Production Smoke Test Results\n")
        f.write(f"Date: {timestamp}\n")
        f.write(f"URL: {BASE_URL}\n\n")
        
        f.write("## Test Results\n")
        for r in results:
            status_str = f"{r['status']}" if r['status'] != "ERROR" else "ERROR"
            icon = "✅" if r["success"] else "❌"
            f.write(f"{icon} {r['endpoint']}: {status_str} - {r['description']}\n")
        
        # Summary
        success_count = sum(1 for r in results if r["success"])
        total_count = len(results)
        f.write(f"\n## Summary\n")
        f.write(f"Passed: {success_count}/{total_count}\n")
        
        # Check for 5xx
        errors_5xx = [r for r in results if isinstance(r.get("status"), int) and r["status"] >= 500]
        if errors_5xx:
            f.write(f"\n## ⚠️  5xx Errors Found\n")
            for err in errors_5xx:
                f.write(f"- {err['endpoint']}: {err['status']}\n")
        else:
            f.write(f"\n## ✅ No 5xx Errors\n")

if __name__ == "__main__":
    results = []
    
    endpoints = [
        ("/", "GET", "Home page"),
        ("/login", "GET", "Login page"),
        ("/workers", "GET", "Workers page"),
        ("/api/workers", "GET", "Workers API"),
        ("/jobs", "GET", "Jobs page"),
        ("/contracts", "GET", "Contracts page"),
        ("/messages", "GET", "Messages page"),
        ("/_health", "GET", "Health check"),
        ("/_ready", "GET", "Ready check"),
    ]
    
    print(f"Running smoke tests on {BASE_URL}")
    print("=" * 60)
    
    for path, method, description in endpoints:
        url = f"{BASE_URL}{path}"
        try:
            if method == "GET":
                response = requests.get(url, timeout=10, allow_redirects=False)
            
            status = response.status_code
            
            # For auth-protected pages, 302 redirect to login is OK
            if status == 302 and path not in ["/_health", "/_ready", "/", "/login"]:
                status_msg = "302 (Auth redirect - OK)"
                success = True
            elif status < 500:
                status_msg = f"{status} (OK)"
                success = True
            else:
                status_msg = f"{status} (ERROR)"
                success = False
            
            result = {
                "endpoint": path,
                "status": status,
                "success": success,
                "description": description
            }
            results.append(result)
            
            icon = "✅" if success else "❌"
            print(f"{icon} {method} {path}: {status_msg} - {description}")
            
        except Exception as e:
            result = {
                "endpoint": path,
                "status": "ERROR",
                "success": False,
                "description": description,
                "error": str(e)
            }
            results.append(result)
            print(f"❌ {method} {path}: ERROR - {e}")
    
    print("=" * 60)
    
    # Save results
    save_results(results)
    
    # Summary
    success_count = sum(1 for r in results if r["success"])
    total_count = len(results)
    
    print(f"\nSummary: {success_count}/{total_count} endpoints passed")
    
    # Check for any 5xx errors
    errors_5xx = [r for r in results if isinstance(r.get("status"), int) and r["status"] >= 500]
    
    if errors_5xx:
        print("\n⚠️  WARNING: Found 5xx errors:")
        for err in errors_5xx:
            print(f"  - {err['endpoint']}: {err['status']}")
        print("\nTest FAILED - 5xx errors detected")
        exit(1)
    else:
        print("\n✅ No 5xx errors found!")
        print("Test PASSED")
        exit(0)
