"""
Test script for custom task type API endpoints
"""
import requests
import json

BASE_URL = "http://localhost:8000"

# Test credentials (assuming admin user exists)
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}")
        print(response.json())
        return None


def test_get_all_task_types(token, project_id=1):
    """Test GET /projects/{project_id}/custom-task-types"""
    print("\n=== Test: Get All Task Types ===")
    headers = {"Authorization": f"Bearer {token}"}
    response = requests.get(f"{BASE_URL}/projects/{project_id}/custom-task-types", headers=headers)
    print(f"Status: {response.status_code}")
    print(f"Response: {json.dumps(response.json(), indent=2)}")
    return response.json()


def test_add_custom_task_type(token, project_id=1, task_type="grooming", category="asset"):
    """Test POST /projects/{project_id}/custom-task-types"""
    print(f"\n=== Test: Add Custom Task Type '{task_type}' ===")
    headers = {"Authorization": f"Bearer {token}"}
    data = {
        "task_type": task_type,
        "category": category
    }
    response = requests.post(
        f"{BASE_URL}/projects/{project_id}/custom-task-types",
        headers=headers,
        json=data
    )
    print(f"Status: {response.status_code}")
    print(f"Response: {json.dumps(response.json(), indent=2)}")
    return response.json()


def test_update_custom_task_type(token, project_id=1, old_name="grooming", new_name="hair_grooming", category="asset"):
    """Test PUT /projects/{project_id}/custom-task-types/{task_type}"""
    print(f"\n=== Test: Update Custom Task Type '{old_name}' to '{new_name}' ===")
    headers = {"Authorization": f"Bearer {token}"}
    data = {
        "old_name": old_name,
        "new_name": new_name,
        "category": category
    }
    response = requests.put(
        f"{BASE_URL}/projects/{project_id}/custom-task-types/{old_name}",
        headers=headers,
        json=data
    )
    print(f"Status: {response.status_code}")
    print(f"Response: {json.dumps(response.json(), indent=2)}")
    return response.json()


def test_delete_custom_task_type(token, project_id=1, task_type="hair_grooming", category="asset"):
    """Test DELETE /projects/{project_id}/custom-task-types/{task_type}"""
    print(f"\n=== Test: Delete Custom Task Type '{task_type}' ===")
    headers = {"Authorization": f"Bearer {token}"}
    response = requests.delete(
        f"{BASE_URL}/projects/{project_id}/custom-task-types/{task_type}?category={category}",
        headers=headers
    )
    print(f"Status: {response.status_code}")
    print(f"Response: {json.dumps(response.json(), indent=2)}")
    return response.json()


def test_validation_errors(token, project_id=1):
    """Test validation errors"""
    print("\n=== Test: Validation Errors ===")
    headers = {"Authorization": f"Bearer {token}"}
    
    # Test invalid task type name (too short)
    print("\n1. Invalid task type name (too short):")
    data = {"task_type": "ab", "category": "asset"}
    response = requests.post(
        f"{BASE_URL}/projects/{project_id}/custom-task-types",
        headers=headers,
        json=data
    )
    print(f"Status: {response.status_code}")
    print(f"Response: {json.dumps(response.json(), indent=2)}")
    
    # Test invalid task type name (uppercase)
    print("\n2. Invalid task type name (uppercase):")
    data = {"task_type": "GroomingTask", "category": "asset"}
    response = requests.post(
        f"{BASE_URL}/projects/{project_id}/custom-task-types",
        headers=headers,
        json=data
    )
    print(f"Status: {response.status_code}")
    print(f"Response: {json.dumps(response.json(), indent=2)}")
    
    # Test duplicate standard task type
    print("\n3. Duplicate standard task type:")
    data = {"task_type": "modeling", "category": "asset"}
    response = requests.post(
        f"{BASE_URL}/projects/{project_id}/custom-task-types",
        headers=headers,
        json=data
    )
    print(f"Status: {response.status_code}")
    print(f"Response: {json.dumps(response.json(), indent=2)}")


def run_all_tests():
    """Run all tests"""
    print("=== Custom Task Type API Tests ===")
    
    # Login
    token = login()
    if not token:
        print("Failed to login. Exiting.")
        return
    
    print(f"\n✓ Logged in successfully")
    
    # Test 1: Get initial task types
    test_get_all_task_types(token)
    
    # Test 2: Add custom task types
    test_add_custom_task_type(token, task_type="grooming", category="asset")
    test_add_custom_task_type(token, task_type="lookdev", category="asset")
    test_add_custom_task_type(token, task_type="previz", category="shot")
    test_add_custom_task_type(token, task_type="matchmove", category="shot")
    
    # Test 3: Get updated task types
    test_get_all_task_types(token)
    
    # Test 4: Update custom task type
    test_update_custom_task_type(token, old_name="grooming", new_name="hair_grooming", category="asset")
    
    # Test 5: Get task types after update
    test_get_all_task_types(token)
    
    # Test 6: Delete custom task type
    test_delete_custom_task_type(token, task_type="hair_grooming", category="asset")
    test_delete_custom_task_type(token, task_type="lookdev", category="asset")
    
    # Test 7: Get final task types
    test_get_all_task_types(token)
    
    # Test 8: Validation errors
    test_validation_errors(token)
    
    print("\n=== All Tests Completed ===")


if __name__ == "__main__":
    run_all_tests()
