#!/usr/bin/env python3
"""
No-500 Smoke Test
Iterates all public/user routes and asserts no 500 errors
"""

import sys
import os
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import requests
from datetime import datetime
import json

BASE_URL = "http://127.0.0.1:5001"

def test_all_routes():
    """Test all routes for 500 errors"""
    
    # Routes to test (from check_routes.py output)
    test_routes = [
        ('GET', '/'),
        ('GET', '/login'),
        ('GET', '/register'),
        ('GET', '/dashboard'),
        ('GET', '/profile'),
        ('GET', '/jobs'),
        ('GET', '/contracts'),
        ('GET', '/applications'),
        ('GET', '/api'),
        ('GET', '/api/health'),
        ('GET', '/health'),
        ('GET', '/test'),
        ('GET', '/_health'),
        ('GET', '/_ready'),
        ('GET', '/_internal/status'),
        ('GET', '/api/marketplace/categories'),
        ('GET', '/api/marketplace/jobs'),
        ('GET', '/api/auth/me'),
        ('GET', '/api/gamification/leaderboards/weekly'),
    ]
    
    results = []
    session = requests.Session()
    
    print(f"\nNO-500 SMOKE TEST - {datetime.now()}")
    print("=" * 60)
    print(f"Testing {BASE_URL}")
    print("-" * 60)
    
    error_500_count = 0
    success_count = 0
    redirect_count = 0
    not_found_count = 0
    
    for method, path in test_routes:
        try:
            response = session.request(method, f"{BASE_URL}{path}", 
                                      allow_redirects=False, timeout=5)
            status = response.status_code
            
            if status >= 500:
                result = "ERROR_500"
                error_500_count += 1
                symbol = "[X]"
            elif status in [200, 201]:
                result = "OK"
                success_count += 1
                symbol = "[OK]"
            elif status in [301, 302, 303, 307, 308]:
                result = "REDIRECT"
                redirect_count += 1
                symbol = "[->]"
            elif status == 404:
                result = "NOT_FOUND"
                not_found_count += 1
                symbol = "[?]"
            else:
                result = f"STATUS_{status}"
                symbol = "[!]"
            
            print(f"{symbol} {method:4} {path:40} -> {status:3} {result}")
            
            results.append({
                "method": method,
                "path": path,
                "status": status,
                "result": result,
                "timestamp": datetime.now().isoformat()
            })
            
        except Exception as e:
            print(f"[E] {method:4} {path:40} -> ERROR: {str(e)[:30]}")
            results.append({
                "method": method,
                "path": path,
                "status": "ERROR",
                "result": "EXCEPTION",
                "error": str(e),
                "timestamp": datetime.now().isoformat()
            })
    
    # Summary
    print("\n" + "=" * 60)
    print("SUMMARY")
    print("-" * 60)
    print(f"Total routes tested: {len(test_routes)}")
    print(f"Success (200/201):   {success_count}")
    print(f"Redirects (3xx):     {redirect_count}")
    print(f"Not Found (404):     {not_found_count}")
    print(f"Server Errors (5xx): {error_500_count}")
    
    # Final verdict
    print("\n" + "=" * 60)
    if error_500_count > 0:
        print("FAIL: 500 ERRORS DETECTED!")
        verdict = "FAIL"
    else:
        print("PASS: NO 500 ERRORS!")
        verdict = "PASS"
    print("=" * 60)
    
    # Save results
    report = {
        "test": "no_500_smoke_test",
        "timestamp": datetime.now().isoformat(),
        "base_url": BASE_URL,
        "verdict": verdict,
        "summary": {
            "total_tested": len(test_routes),
            "success_count": success_count,
            "redirect_count": redirect_count,
            "not_found_count": not_found_count,
            "error_500_count": error_500_count
        },
        "results": results
    }
    
    os.makedirs("evidence/phaseB", exist_ok=True)
    with open("evidence/phaseB/no_500_smoke_test.json", "w") as f:
        json.dump(report, f, indent=2)
    
    return error_500_count == 0

if __name__ == "__main__":
    success = test_all_routes()
    sys.exit(0 if success else 1)
