#!/usr/bin/env python3
"""
Phase 4: Simple endpoint verification for RateRight
Tests all critical endpoints and captures status codes
"""

import requests
from datetime import datetime

# Test configuration
BASE_URL = "http://127.0.0.1:5001"

def test_endpoints():
    """Test all critical endpoints"""
    
    endpoints = [
        # Auth endpoints
        ("GET", "/", "Home page"),
        ("GET", "/auth/login", "Login page"),
        ("GET", "/auth/register", "Register page"),
        ("GET", "/dashboard", "Dashboard (redirect if not logged in)"),
        
        # API endpoints
        ("GET", "/api/workers", "Workers API"),
        ("GET", "/workers", "Workers page"),
        
        # Other critical pages
        ("GET", "/jobs", "Jobs listing"),
        ("GET", "/contracts", "Contracts listing"),
        ("GET", "/messages", "Messages page"),
        ("GET", "/payments", "Payments page"),
        ("GET", "/scheduling/calendar", "Calendar page"),
    ]
    
    results = []
    print(f"\n{'='*60}")
    print(f"PHASE 4: ENDPOINT VERIFICATION - {datetime.now()}")
    print(f"{'='*60}\n")
    print(f"Testing {BASE_URL}")
    print(f"{'-'*60}")
    
    # Test server availability
    try:
        resp = requests.get(BASE_URL, timeout=3)
        print(f"✅ Server is running (status: {resp.status_code})\n")
    except Exception as e:
        print(f"❌ Server is not responding: {e}\n")
        return False
    
    # Test each endpoint
    print(f"{'Endpoint':<30} {'Status':<10} {'Result':<10}")
    print(f"{'-'*60}")
    
    session = requests.Session()
    
    for method, path, description in endpoints:
        try:
            if method == "GET":
                resp = session.get(f"{BASE_URL}{path}", allow_redirects=False, timeout=3)
            else:
                resp = session.request(method, f"{BASE_URL}{path}", allow_redirects=False, timeout=3)
            
            status = resp.status_code
            
            # Determine if the status is acceptable
            if status in [200, 302, 303, 401]:  # OK, redirect, or auth required
                result = "PASS"
                emoji = "✅"
            elif status == 404:
                result = "MISSING"
                emoji = "⚠️"
            elif status >= 500:
                result = "ERROR"
                emoji = "❌"
            else:
                result = "CHECK"
                emoji = "⚠️"
            
            print(f"{emoji} {path:<28} {status:<10} {result:<10}")
            
            results.append({
                "path": path,
                "method": method,
                "description": description,
                "status": status,
                "result": result
            })
            
        except Exception as e:
            print(f"❌ {path:<28} ERROR      FAIL")
            results.append({
                "path": path,
                "method": method,
                "description": description,
                "status": "ERROR",
                "result": "FAIL",
                "error": str(e)
            })
    
    # Summary
    print(f"\n{'='*60}")
    print("SUMMARY")
    print(f"{'='*60}")
    
    pass_count = sum(1 for r in results if r['result'] == 'PASS')
    missing_count = sum(1 for r in results if r['result'] == 'MISSING')
    error_count = sum(1 for r in results if r['result'] in ['ERROR', 'FAIL'])
    
    print(f"✅ Passed:  {pass_count}/{len(results)}")
    print(f"⚠️  Missing: {missing_count}/{len(results)}")
    print(f"❌ Errors:  {error_count}/{len(results)}")
    
    # Check for 500 errors
    has_500_errors = any(r.get('status', 0) >= 500 for r in results)
    
    print(f"\n{'='*60}")
    if has_500_errors:
        print("❌ CRITICAL: 500 ERRORS DETECTED!")
    elif error_count > 0:
        print("⚠️  WARNING: Some endpoints have issues")
    else:
        print("✅ SUCCESS: No 500 errors detected!")
    print(f"{'='*60}\n")
    
    # Save results
    import json
    with open("evidence/phase4/endpoint_verification.json", "w") as f:
        json.dump({
            "timestamp": datetime.now().isoformat(),
            "base_url": BASE_URL,
            "results": results,
            "summary": {
                "total": len(results),
                "passed": pass_count,
                "missing": missing_count,
                "errors": error_count,
                "has_500_errors": has_500_errors
            }
        }, f, indent=2)
    
    return not has_500_errors

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