#!/usr/bin/env python3
"""
Test script for default asset task creation functionality.
Tests Requirements: 17.1, 17.2, 17.3, 17.4, 17.5, 17.6, 17.7
"""

import requests
import json

# Configuration
BASE_URL = "http://localhost:8000"
LOGIN_URL = f"{BASE_URL}/auth/login"
ASSETS_URL = f"{BASE_URL}/assets/"
TASKS_URL = f"{BASE_URL}/tasks/"

def test_default_asset_tasks():
    print("Testing Default Asset Task Creation")
    print("=" * 60)
    
    # Login first
    print("\n1. Logging in as coordinator...")
    login_data = {
        "email": "admin@vfx.com",
        "password": "admin123"
    }
    
    response = requests.post(LOGIN_URL, json=login_data)
    if response.status_code != 200:
        print(f"❌ Login failed: {response.status_code}")
        print(response.text)
        return
    
    token_data = response.json()
    token = token_data["access_token"]
    headers = {"Authorization": f"Bearer {token}"}
    print("✅ Login successful")
    
    # Get projects
    print("\n2. Getting projects...")
    projects_response = requests.get(f"{BASE_URL}/projects/", headers=headers)
    if projects_response.status_code != 200:
        print(f"❌ Failed to get projects: {projects_response.status_code}")
        return
    
    projects = projects_response.json()
    if not projects:
        print("❌ No projects found")
        return
    
    project_id = projects[0]["id"]
    print(f"✅ Using project ID: {project_id}")
    
    # Test 1: Get default tasks for each category (Requirement 17.1, 17.2)
    print("\n3. Testing default task templates for each category...")
    categories = ["characters", "props", "sets", "vehicles"]
    expected_tasks = {
        "characters": ["modeling", "surfacing", "rigging"],
        "props": ["modeling", "surfacing"],
        "sets": ["modeling", "surfacing"],
        "vehicles": ["modeling", "surfacing", "rigging"]
    }
    
    for category in categories:
        response = requests.get(
            f"{ASSETS_URL}default-tasks/{category}",
            params={"project_id": project_id},
            headers=headers
        )
        
        if response.status_code == 200:
            tasks = response.json()
            expected = expected_tasks[category]
            if set(tasks[:len(expected)]) == set(expected):
                print(f"✅ {category.capitalize()}: {tasks}")
            else:
                print(f"❌ {category.capitalize()}: Expected {expected}, got {tasks}")
        else:
            print(f"❌ Failed to get default tasks for {category}: {response.status_code}")
    
    # Test 2: Create asset with default tasks (Requirement 17.1, 17.4, 17.6)
    print("\n4. Creating character asset with default tasks...")
    import time
    timestamp = int(time.time())
    asset_data = {
        "name": f"Test Character Hero {timestamp}",
        "category": "characters",
        "description": "Test character for default task creation",
        "status": "not_started",
        "create_default_tasks": True
    }
    
    response = requests.post(
        f"{ASSETS_URL}?project_id={project_id}",
        json=asset_data,
        headers=headers
    )
    
    if response.status_code == 201:
        asset = response.json()
        asset_id = asset["id"]
        task_count = asset.get("task_count", 0)
        print(f"✅ Asset created with ID: {asset_id}")
        print(f"   Task count: {task_count}")
        
        if task_count == 3:  # Characters should have 3 tasks
            print("✅ Correct number of default tasks created")
        else:
            print(f"❌ Expected 3 tasks, got {task_count}")
    else:
        print(f"❌ Failed to create asset: {response.status_code}")
        print(response.text)
        return
    
    # Test 3: Verify tasks were created with correct naming (Requirement 17.6)
    print("\n5. Verifying created tasks...")
    response = requests.get(
        f"{ASSETS_URL}{asset_id}/task-status",
        headers=headers
    )
    
    if response.status_code == 200:
        task_details = response.json()
        print(f"✅ Found {len(task_details)} tasks for asset")
        
        expected_task_types = ["modeling", "surfacing", "rigging"]
        found_task_types = [task["task_type"] for task in task_details]
        
        # Get full task details to verify naming
        for task_info in task_details:
            task_id = task_info["task_id"]
            task_response = requests.get(f"{TASKS_URL}{task_id}", headers=headers)
            if task_response.status_code == 200:
                task = task_response.json()
                print(f"   - {task['name']} ({task['task_type']}) - Status: {task['status']}")
                
                # Verify naming convention (Requirement 17.6)
                expected_name = f"{asset_data['name']} - {task['task_type'].title()}"
                if task['name'] == expected_name:
                    print(f"     ✅ Correct naming convention")
                else:
                    print(f"     ❌ Expected name: {expected_name}, got: {task['name']}")
                
                # Verify unassigned (Requirement 17.7)
                if task.get('assigned_user_id') is None:
                    print(f"     ✅ Task is unassigned")
                else:
                    print(f"     ❌ Task should be unassigned")
        
        if set(found_task_types) == set(expected_task_types):
            print("✅ All expected task types created")
        else:
            print(f"❌ Expected {expected_task_types}, got {found_task_types}")
    else:
        print(f"❌ Failed to get tasks: {response.status_code}")
    
    # Test 4: Create asset with custom task selection (Requirement 17.3, 17.5)
    print("\n6. Creating prop asset with custom task selection...")
    timestamp = int(time.time())
    asset_data = {
        "name": f"Test Prop Sword {timestamp}",
        "category": "props",
        "description": "Test prop with custom task selection",
        "status": "not_started",
        "create_default_tasks": True,
        "selected_task_types": ["modeling"]  # Only modeling, skip surfacing
    }
    
    response = requests.post(
        f"{ASSETS_URL}?project_id={project_id}",
        json=asset_data,
        headers=headers
    )
    
    if response.status_code == 201:
        asset = response.json()
        asset_id = asset["id"]
        task_count = asset.get("task_count", 0)
        print(f"✅ Asset created with ID: {asset_id}")
        print(f"   Task count: {task_count}")
        
        if task_count == 1:  # Only modeling task
            print("✅ Custom task selection works correctly")
        else:
            print(f"❌ Expected 1 task, got {task_count}")
        
        # Verify only modeling task was created
        response = requests.get(
            f"{ASSETS_URL}{asset_id}/task-status",
            headers=headers
        )
        
        if response.status_code == 200:
            task_details = response.json()
            if len(task_details) == 1 and task_details[0]["task_type"] == "modeling":
                print("✅ Only selected task type was created")
            else:
                print(f"❌ Expected only modeling task, got: {[t['task_type'] for t in task_details]}")
    else:
        print(f"❌ Failed to create asset: {response.status_code}")
        print(response.text)
    
    # Test 5: Create asset without default tasks
    print("\n7. Creating asset without default tasks...")
    timestamp = int(time.time())
    asset_data = {
        "name": f"Test Set Environment {timestamp}",
        "category": "sets",
        "description": "Test set without default tasks",
        "status": "not_started",
        "create_default_tasks": False
    }
    
    response = requests.post(
        f"{ASSETS_URL}?project_id={project_id}",
        json=asset_data,
        headers=headers
    )
    
    if response.status_code == 201:
        asset = response.json()
        asset_id = asset["id"]
        task_count = asset.get("task_count", 0)
        print(f"✅ Asset created with ID: {asset_id}")
        print(f"   Task count: {task_count}")
        
        if task_count == 0:
            print("✅ No tasks created when create_default_tasks is False")
        else:
            print(f"❌ Expected 0 tasks, got {task_count}")
    else:
        print(f"❌ Failed to create asset: {response.status_code}")
        print(response.text)
    
    # Test 6: Verify different categories have correct default tasks
    print("\n8. Testing default tasks for vehicle category...")
    timestamp = int(time.time())
    asset_data = {
        "name": f"Test Vehicle Spaceship {timestamp}",
        "category": "vehicles",
        "description": "Test vehicle with default tasks",
        "status": "not_started",
        "create_default_tasks": True
    }
    
    response = requests.post(
        f"{ASSETS_URL}?project_id={project_id}",
        json=asset_data,
        headers=headers
    )
    
    if response.status_code == 201:
        asset = response.json()
        task_count = asset.get("task_count", 0)
        
        if task_count == 3:  # Vehicles should have modeling, surfacing, rigging
            print("✅ Vehicle category has correct default tasks (3)")
        else:
            print(f"❌ Expected 3 tasks for vehicle, got {task_count}")
    else:
        print(f"❌ Failed to create vehicle asset: {response.status_code}")
    
    print("\n" + "=" * 60)
    print("✅ All default asset task creation tests completed!")
    print("\nRequirements tested:")
    print("  ✅ 17.1 - Automatic task generation based on asset category")
    print("  ✅ 17.2 - Default task templates for each category")
    print("  ✅ 17.3 - Customizable task creation options")
    print("  ✅ 17.4 - Default task naming conventions")
    print("  ✅ 17.5 - API endpoint for retrieving default tasks")
    print("  ✅ 17.6 - Proper task naming")
    print("  ✅ 17.7 - Unassigned task creation")

if __name__ == "__main__":
    test_default_asset_tasks()
