#!/usr/bin/env python3
"""
Diagnostic Performance Test

This test helps diagnose the performance issues by testing different scenarios.
"""

import requests
import time
import traceback

BASE_URL = "http://localhost:8000"

def login():
    """Login and get access token"""
    response = requests.post(f"{BASE_URL}/auth/login", json={
        "email": "admin@vfx.com",
        "password": "admin123"
    })
    if response.status_code == 200:
        return response.json()["access_token"]
    return None

def test_basic_endpoints():
    """Test basic endpoint functionality."""
    print("=== Basic Endpoint Test ===")
    
    token = login()
    if not token:
        print("❌ Login failed")
        return
    
    headers = {"Authorization": f"Bearer {token}"}
    
    # Test 1: Simple shot endpoint without parameters
    print("Testing basic shot endpoint...")
    try:
        start_time = time.time()
        response = requests.get(f"{BASE_URL}/shots/", headers=headers)
        end_time = time.time()
        
        print(f"  Status: {response.status_code}")
        print(f"  Time: {(end_time - start_time) * 1000:.2f}ms")
        
        if response.status_code == 200:
            shots = response.json()
            print(f"  Shots returned: {len(shots)}")
            if shots:
                print(f"  Sample shot keys: {list(shots[0].keys())}")
        else:
            print(f"  Error: {response.text}")
    except Exception as e:
        print(f"  Exception: {e}")
        traceback.print_exc()
    
    # Test 2: Simple asset endpoint without parameters
    print("\nTesting basic asset endpoint...")
    try:
        start_time = time.time()
        response = requests.get(f"{BASE_URL}/assets/", headers=headers)
        end_time = time.time()
        
        print(f"  Status: {response.status_code}")
        print(f"  Time: {(end_time - start_time) * 1000:.2f}ms")
        
        if response.status_code == 200:
            assets = response.json()
            print(f"  Assets returned: {len(assets)}")
            if assets:
                print(f"  Sample asset keys: {list(assets[0].keys())}")
        else:
            print(f"  Error: {response.text}")
    except Exception as e:
        print(f"  Exception: {e}")
        traceback.print_exc()
    
    # Test 3: Shot endpoint with small limit
    print("\nTesting shot endpoint with limit=1...")
    try:
        start_time = time.time()
        response = requests.get(f"{BASE_URL}/shots/?limit=1", headers=headers)
        end_time = time.time()
        
        print(f"  Status: {response.status_code}")
        print(f"  Time: {(end_time - start_time) * 1000:.2f}ms")
        
        if response.status_code == 200:
            shots = response.json()
            print(f"  Shots returned: {len(shots)}")
        else:
            print(f"  Error: {response.text}")
    except Exception as e:
        print(f"  Exception: {e}")
    
    # Test 4: Asset endpoint with small limit
    print("\nTesting asset endpoint with limit=1...")
    try:
        start_time = time.time()
        response = requests.get(f"{BASE_URL}/assets/?limit=1", headers=headers)
        end_time = time.time()
        
        print(f"  Status: {response.status_code}")
        print(f"  Time: {(end_time - start_time) * 1000:.2f}ms")
        
        if response.status_code == 200:
            assets = response.json()
            print(f"  Assets returned: {len(assets)}")
        else:
            print(f"  Error: {response.text}")
    except Exception as e:
        print(f"  Exception: {e}")

def test_with_project_filter():
    """Test with project filtering to see if that helps performance."""
    print("\n=== Project Filter Test ===")
    
    token = login()
    if not token:
        print("❌ Login failed")
        return
    
    headers = {"Authorization": f"Bearer {token}"}
    
    # Get a project ID first
    try:
        response = requests.get(f"{BASE_URL}/projects/", headers=headers)
        if response.status_code == 200:
            projects = response.json()
            if projects:
                project_id = projects[0]['id']
                print(f"Using project ID: {project_id}")
                
                # Test shots with project filter
                print("Testing shots with project filter...")
                start_time = time.time()
                response = requests.get(f"{BASE_URL}/shots/?project_id={project_id}&limit=10", headers=headers)
                end_time = time.time()
                
                print(f"  Status: {response.status_code}")
                print(f"  Time: {(end_time - start_time) * 1000:.2f}ms")
                
                if response.status_code == 200:
                    shots = response.json()
                    print(f"  Shots returned: {len(shots)}")
                
                # Test assets with project filter
                print("Testing assets with project filter...")
                start_time = time.time()
                response = requests.get(f"{BASE_URL}/assets/?project_id={project_id}&limit=10", headers=headers)
                end_time = time.time()
                
                print(f"  Status: {response.status_code}")
                print(f"  Time: {(end_time - start_time) * 1000:.2f}ms")
                
                if response.status_code == 200:
                    assets = response.json()
                    print(f"  Assets returned: {len(assets)}")
                else:
                    print(f"  Error: {response.text}")
            else:
                print("No projects found")
        else:
            print(f"Failed to get projects: {response.status_code}")
    except Exception as e:
        print(f"Exception: {e}")
        traceback.print_exc()

def test_individual_endpoints():
    """Test individual shot/asset by ID."""
    print("\n=== Individual Item Test ===")
    
    token = login()
    if not token:
        print("❌ Login failed")
        return
    
    headers = {"Authorization": f"Bearer {token}"}
    
    # Get a shot ID and test individual shot
    try:
        response = requests.get(f"{BASE_URL}/shots/?limit=1", headers=headers)
        if response.status_code == 200:
            shots = response.json()
            if shots:
                shot_id = shots[0]['id']
                print(f"Testing individual shot {shot_id}...")
                
                start_time = time.time()
                response = requests.get(f"{BASE_URL}/shots/{shot_id}", headers=headers)
                end_time = time.time()
                
                print(f"  Status: {response.status_code}")
                print(f"  Time: {(end_time - start_time) * 1000:.2f}ms")
                
                if response.status_code == 200:
                    shot = response.json()
                    print(f"  Shot: {shot['name']}")
                    print(f"  Task count: {shot.get('task_count', 'N/A')}")
    except Exception as e:
        print(f"Exception: {e}")

if __name__ == "__main__":
    print("Diagnostic Performance Test")
    print("=" * 40)
    
    # Check server
    try:
        response = requests.get(f"{BASE_URL}/docs", timeout=5)
        print(f"Server status: {response.status_code}")
    except Exception as e:
        print(f"❌ Server connection failed: {e}")
        exit(1)
    
    test_basic_endpoints()
    test_with_project_filter()
    test_individual_endpoints()