#!/usr/bin/env python3
"""
Test script to verify API connection and authentication flow.
"""

import requests
import json

BASE_URL = "http://localhost:8000"

def test_api_connection():
    """Test the API connection and authentication."""
    
    print("Testing VFX Project Management API Connection")
    print("=" * 50)
    
    # Test 1: Health check
    print("1. Testing health endpoint...")
    try:
        response = requests.get(f"{BASE_URL}/health")
        if response.status_code == 200:
            print("   ✅ Health check passed")
            print(f"   Response: {response.json()}")
        else:
            print(f"   ❌ Health check failed: {response.status_code}")
            return False
    except Exception as e:
        print(f"   ❌ Health check error: {e}")
        return False
    
    # Test 2: Login
    print("\n2. Testing login...")
    login_data = {
        "email": "admin@vfx.com",
        "password": "admin123"
    }
    
    try:
        response = requests.post(f"{BASE_URL}/auth/login", json=login_data)
        if response.status_code == 200:
            print("   ✅ Login successful")
            auth_data = response.json()
            access_token = auth_data.get("access_token")
            print(f"   Token received: {access_token[:20]}...")
        else:
            print(f"   ❌ Login failed: {response.status_code}")
            print(f"   Response: {response.text}")
            return False
    except Exception as e:
        print(f"   ❌ Login error: {e}")
        return False
    
    # Test 3: Get current user
    print("\n3. Testing get current user...")
    headers = {"Authorization": f"Bearer {access_token}"}
    
    try:
        response = requests.get(f"{BASE_URL}/users/me", headers=headers)
        if response.status_code == 200:
            print("   ✅ Get current user successful")
            user_data = response.json()
            print(f"   User: {user_data.get('email')} ({user_data.get('role')})")
        else:
            print(f"   ❌ Get current user failed: {response.status_code}")
            print(f"   Response: {response.text}")
            return False
    except Exception as e:
        print(f"   ❌ Get current user error: {e}")
        return False
    
    # Test 4: Get projects
    print("\n4. Testing get projects...")
    
    try:
        response = requests.get(f"{BASE_URL}/projects/", headers=headers)
        if response.status_code == 200:
            print("   ✅ Get projects successful")
            projects = response.json()
            print(f"   Found {len(projects)} projects:")
            for project in projects:
                print(f"     - {project.get('name')} ({project.get('code_name')})")
        else:
            print(f"   ❌ Get projects failed: {response.status_code}")
            print(f"   Response: {response.text}")
            return False
    except Exception as e:
        print(f"   ❌ Get projects error: {e}")
        return False
    
    print("\n✅ All API tests passed!")
    print("\nFrontend should be able to:")
    print("- Login with admin@vfx.com / admin123")
    print("- Load projects from the API")
    print("- Display project data correctly")
    
    return True

if __name__ == "__main__":
    test_api_connection()