"""
Test script for verifying task type in use protection
"""
import requests
import json

BASE_URL = "http://localhost:8000"

# Test credentials
LOGIN_DATA = {
    "email": "admin@vfx.com",
    "password": "admin123"
}


def login():
    """Login and get access token"""
    response = requests.post(f"{BASE_URL}/auth/login", json=LOGIN_DATA)
    if response.status_code == 200:
        return response.json()["access_token"]
    else:
        print(f"Login failed: {response.status_code}")
        return None


def test_task_type_in_use():
    """Test that we cannot delete a task type that is in use"""
    print("=== Test: Task Type In Use Protection ===\n")
    
    token = login()
    if not token:
        return
    
    headers = {"Authorization": f"Bearer {token}"}
    project_id = 1
    
    # Step 1: Ensure custom task type exists
    print("1. Ensuring custom task type 'fx_setup' exists...")
    response = requests.post(
        f"{BASE_URL}/projects/{project_id}/custom-task-types",
        headers=headers,
        json={"task_type": "fx_setup", "category": "asset"}
    )
    if response.status_code == 201:
        print(f"   Created new custom task type")
    elif response.status_code == 409:
        print(f"   Custom task type already exists (OK)")
    else:
        print(f"   Unexpected status: {response.status_code}")
        print(f"   Response: {response.json()}")
        return
    print()
    
    # Step 2: Use a hardcoded asset ID (assuming asset 1 exists)
    asset_id = 1
    print(f"2. Using asset ID: {asset_id}\n")
    
    # Step 3: Create a task with the custom task type
    print("3. Creating task with custom task type 'fx_setup'...")
    response = requests.post(
        f"{BASE_URL}/tasks",
        headers=headers,
        json={
            "project_id": project_id,
            "asset_id": asset_id,
            "task_type": "fx_setup",
            "name": "FX Setup Task",
            "description": "Test task with custom type"
        }
    )
    print(f"   Status: {response.status_code}")
    if response.status_code in [200, 201]:
        task_id = response.json()["id"]
        print(f"   Created task ID: {task_id}\n")
    else:
        print(f"   Error: {response.json()}\n")
        return
    
    # Step 4: Try to delete the custom task type (should fail)
    print("4. Attempting to delete custom task type 'fx_setup' (should fail)...")
    response = requests.delete(
        f"{BASE_URL}/projects/{project_id}/custom-task-types/fx_setup?category=asset",
        headers=headers
    )
    print(f"   Status: {response.status_code}")
    print(f"   Response: {json.dumps(response.json(), indent=2)}\n")
    
    # Step 5: Delete the task
    print("5. Deleting the task...")
    response = requests.delete(f"{BASE_URL}/tasks/{task_id}", headers=headers)
    print(f"   Status: {response.status_code}\n")
    
    # Step 6: Try to delete the custom task type again (should succeed)
    print("6. Attempting to delete custom task type 'fx_setup' again (should succeed)...")
    response = requests.delete(
        f"{BASE_URL}/projects/{project_id}/custom-task-types/fx_setup?category=asset",
        headers=headers
    )
    print(f"   Status: {response.status_code}")
    print(f"   Response: {json.dumps(response.json(), indent=2)}\n")
    
    print("=== Test Completed ===")


if __name__ == "__main__":
    test_task_type_in_use()
