#!/usr/bin/env python3
"""
Comprehensive smoke tests for production deployment
Verifies all features including analytics
"""

import requests
import json
from datetime import datetime

BASE_URL = "https://rateright-au.fly.dev"
ENDPOINTS = {
    "Core Pages": [
        ("/", "Home page"),
        ("/login", "Login page"),
        ("/register", "Registration page"),
        ("/workers", "Workers page"),
        ("/jobs", "Jobs page"),
        ("/contracts", "Contracts page"),
        ("/messages", "Messages page"),
    ],
    "Analytics Pages": [
        ("/analytics/worker", "Worker Analytics page"),
        ("/analytics/client", "Client Analytics page"),
    ],
    "API Endpoints": [
        ("/api", "API Info"),
        ("/api/health", "Health check"),
        ("/api/workers", "Workers API"),
        ("/_health", "System health"),
        ("/_ready", "System ready"),
    ]
}

def test_endpoint(url, description):
    """Test a single endpoint"""
    try:
        response = requests.get(url, timeout=10, allow_redirects=True)
        status_code = response.status_code
        
        # Analytics pages might redirect to login (302) which is OK
        if "/analytics/" in url and status_code == 302:
            return "✅", f"{description}: {status_code} (Requires login - OK)"
        
        if 200 <= status_code < 400:
            return "✅", f"{description}: {status_code}"
        elif status_code == 404:
            return "❌", f"{description}: 404 NOT FOUND"
        elif status_code >= 500:
            return "🔥", f"{description}: {status_code} SERVER ERROR"
        else:
            return "⚠️", f"{description}: {status_code}"
    except Exception as e:
        return "💥", f"{description}: ERROR - {str(e)}"

def check_button_colors():
    """Check if buttons are blue (not orange)"""
    try:
        response = requests.get(f"{BASE_URL}/", timeout=10)
        content = response.text.lower()
        
        # Check for orange button styles that shouldn't be there
        has_orange = "btn-orange" in content or "background-color: #f97316" in content
        has_blue = "btn-primary" in content or "--btn-primary-bg" in content
        
        if has_orange:
            return "⚠️", "Orange buttons detected - CSS might not be applied correctly"
        elif has_blue:
            return "✅", "Blue button styles confirmed"
        else:
            return "❓", "Could not verify button colors"
    except Exception as e:
        return "💥", f"Error checking button colors: {str(e)}"

def main():
    """Run all smoke tests"""
    print("=" * 60)
    print("COMPREHENSIVE SMOKE TEST REPORT")
    print(f"Target: {BASE_URL}")
    print(f"Time: {datetime.now().isoformat()}")
    print("=" * 60)
    
    results = {
        "passed": 0,
        "failed": 0,
        "errors": 0,
        "warnings": 0,
        "details": []
    }
    
    # Test all endpoints
    for category, endpoints in ENDPOINTS.items():
        print(f"\n{category}:")
        print("-" * 40)
        
        for endpoint, description in endpoints:
            url = f"{BASE_URL}{endpoint}"
            status, message = test_endpoint(url, description)
            print(f"{status} {message}")
            
            results["details"].append({
                "category": category,
                "endpoint": endpoint,
                "status": status,
                "message": message
            })
            
            if status == "✅":
                results["passed"] += 1
            elif status == "❌":
                results["failed"] += 1
            elif status == "🔥" or status == "💥":
                results["errors"] += 1
            else:
                results["warnings"] += 1
    
    # Check button colors
    print("\nUI Checks:")
    print("-" * 40)
    status, message = check_button_colors()
    print(f"{status} {message}")
    
    # Summary
    print("\n" + "=" * 60)
    print("SUMMARY:")
    print(f"✅ Passed: {results['passed']}")
    print(f"❌ Failed: {results['failed']}")
    print(f"🔥 Errors: {results['errors']}")
    print(f"⚠️ Warnings: {results['warnings']}")
    
    # Save results
    output_file = "evidence/fly/04_comprehensive_smoke.json"
    with open(output_file, "w") as f:
        json.dump(results, f, indent=2)
    print(f"\nResults saved to: {output_file}")
    
    # Return status
    if results["errors"] > 0:
        print("\n🔥 CRITICAL: Server errors detected!")
        return 1
    elif results["failed"] > 0:
        print("\n❌ FAILED: Some endpoints not accessible")
        return 1
    else:
        print("\n✅ SUCCESS: All critical checks passed!")
        return 0

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