"""
Test script for project settings API endpoints
Tests the complete project settings functionality
"""
import requests
import json

BASE_URL = "http://localhost:8000"

def get_auth_token():
    """Login and get authentication token"""
    # Login with admin user
    response = requests.post(
        f"{BASE_URL}/auth/login",
        json={
            "email": "admin@vfx.com",
            "password": "admin123"
        }
    )
    
    if response.status_code != 200:
        print(f"❌ Login failed: {response.status_code}")
        print(response.text)
        return None
    
    return response.json()["access_token"]

def test_project_settings():
    """Test project settings endpoints"""
    print("Logging in...")
    token = get_auth_token()
    if not token:
        return False
    
    headers = {"Authorization": f"Bearer {token}"}
    print("✓ Logged in successfully")
    
    # Get first project
    print("\nGetting projects...")
    response = requests.get(f"{BASE_URL}/projects/", headers=headers)
    if response.status_code != 200:
        print(f"❌ Failed to get projects: {response.status_code}")
        return False
    
    projects = response.json()
    if not projects:
        print("❌ No projects found")
        return False
    
    project_id = projects[0]["id"]
    print(f"✓ Using project: {projects[0]['name']} (ID: {project_id})")
    
    # Test 1: Get project settings (should return defaults)
    print("\n1. Testing GET /projects/{project_id}/settings...")
    response = requests.get(f"{BASE_URL}/projects/{project_id}/settings", headers=headers)
    
    if response.status_code != 200:
        print(f"❌ Failed to get settings: {response.status_code}")
        print(response.text)
        return False
    
    settings = response.json()
    print("✓ Retrieved project settings:")
    print(json.dumps(settings, indent=2))
    
    # Verify default values
    assert "upload_data_location" in settings
    assert "asset_task_templates" in settings
    assert "shot_task_templates" in settings
    assert "enabled_asset_tasks" in settings
    assert "enabled_shot_tasks" in settings
    print("✓ All required fields present")
    
    # Test 2: Update project settings
    print("\n2. Testing PUT /projects/{project_id}/settings...")
    new_settings = {
        "upload_data_location": "/mnt/projects/test-project/uploads",
        "asset_task_templates": {
            "characters": ["modeling", "surfacing", "rigging"],
            "props": ["modeling", "surfacing"],
            "sets": ["modeling", "surfacing"],
            "vehicles": ["modeling", "surfacing", "rigging"]
        },
        "shot_task_templates": ["layout", "animation", "lighting", "compositing"],
        "enabled_asset_tasks": {
            "characters": ["modeling", "rigging"],
            "props": ["modeling"]
        },
        "enabled_shot_tasks": ["layout", "animation", "lighting"]
    }
    
    response = requests.put(
        f"{BASE_URL}/projects/{project_id}/settings",
        headers=headers,
        json=new_settings
    )
    
    if response.status_code != 200:
        print(f"❌ Failed to update settings: {response.status_code}")
        print(response.text)
        return False
    
    updated_settings = response.json()
    print("✓ Settings updated successfully:")
    print(json.dumps(updated_settings, indent=2))
    
    # Verify updates
    assert updated_settings["upload_data_location"] == "/mnt/projects/test-project/uploads"
    assert len(updated_settings["shot_task_templates"]) == 4
    print("✓ Settings values updated correctly")
    
    # Test 3: Verify persistence
    print("\n3. Verifying settings persistence...")
    response = requests.get(f"{BASE_URL}/projects/{project_id}/settings", headers=headers)
    
    if response.status_code != 200:
        print(f"❌ Failed to verify settings: {response.status_code}")
        return False
    
    verified_settings = response.json()
    assert verified_settings["upload_data_location"] == "/mnt/projects/test-project/uploads"
    assert len(verified_settings["shot_task_templates"]) == 4
    print("✓ Settings persisted correctly")
    
    # Test 4: Partial update
    print("\n4. Testing partial update...")
    partial_update = {
        "upload_data_location": "/new/upload/path"
    }
    
    response = requests.put(
        f"{BASE_URL}/projects/{project_id}/settings",
        headers=headers,
        json=partial_update
    )
    
    if response.status_code != 200:
        print(f"❌ Failed partial update: {response.status_code}")
        print(response.text)
        return False
    
    partial_result = response.json()
    assert partial_result["upload_data_location"] == "/new/upload/path"
    # Other settings should remain unchanged
    assert len(partial_result["shot_task_templates"]) == 4
    print("✓ Partial update successful")
    
    # Test 5: Invalid project ID
    print("\n5. Testing invalid project ID...")
    response = requests.get(f"{BASE_URL}/projects/99999/settings", headers=headers)
    assert response.status_code == 404
    print("✓ Correctly returns 404 for invalid project")
    
    print("\n✅ All tests passed!")
    return True

if __name__ == "__main__":
    print("Testing Project Settings API")
    print("=" * 60)
    try:
        success = test_project_settings()
        if not success:
            print("\n❌ Tests failed")
            exit(1)
    except Exception as e:
        print(f"\n❌ Test error: {e}")
        import traceback
        traceback.print_exc()
        exit(1)
