"""
Test script for creating custom task statuses
"""
import requests
import json

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"]
    else:
        print(f"Login failed: {response.status_code}")
        print(response.text)
        return None

def get_all_statuses(token, project_id):
    """Get all task statuses for a project"""
    headers = {"Authorization": f"Bearer {token}"}
    response = requests.get(
        f"{BASE_URL}/projects/{project_id}/task-statuses",
        headers=headers
    )
    print(f"\n=== GET All Task Statuses (Status: {response.status_code}) ===")
    if response.status_code == 200:
        data = response.json()
        print(f"System statuses: {len(data['system_statuses'])}")
        print(f"Custom statuses: {len(data['statuses'])}")
        print(f"Default status ID: {data['default_status_id']}")
        print("\nCustom statuses:")
        for status in data['statuses']:
            print(f"  - {status['name']} ({status['id']}) - {status['color']} - Order: {status['order']}")
        return data
    else:
        print(f"Error: {response.text}")
        return None

def create_custom_status(token, project_id, name, color=None):
    """Create a new custom task status"""
    headers = {"Authorization": f"Bearer {token}"}
    payload = {"name": name}
    if color:
        payload["color"] = color
    
    response = requests.post(
        f"{BASE_URL}/projects/{project_id}/task-statuses",
        headers=headers,
        json=payload
    )
    print(f"\n=== POST Create Custom Status '{name}' (Status: {response.status_code}) ===")
    if response.status_code == 201:
        data = response.json()
        print(f"Message: {data['message']}")
        print(f"Created status: {data['status']['name']} ({data['status']['id']})")
        print(f"  Color: {data['status']['color']}")
        print(f"  Order: {data['status']['order']}")
        print(f"  Is Default: {data['status']['is_default']}")
        return data
    else:
        print(f"Error: {response.text}")
        return None

def test_validation_errors():
    """Test validation errors"""
    token = login()
    if not token:
        return
    
    project_id = 1
    headers = {"Authorization": f"Bearer {token}"}
    
    # Test 1: Empty name
    print("\n=== Test: Empty name ===")
    response = requests.post(
        f"{BASE_URL}/projects/{project_id}/task-statuses",
        headers=headers,
        json={"name": ""}
    )
    print(f"Status: {response.status_code}")
    print(f"Response: {response.text}")
    
    # Test 2: Invalid color format
    print("\n=== Test: Invalid color format ===")
    response = requests.post(
        f"{BASE_URL}/projects/{project_id}/task-statuses",
        headers=headers,
        json={"name": "Test Status", "color": "invalid"}
    )
    print(f"Status: {response.status_code}")
    print(f"Response: {response.text}")
    
    # Test 3: Duplicate name
    print("\n=== Test: Duplicate name ===")
    # First create a status
    requests.post(
        f"{BASE_URL}/projects/{project_id}/task-statuses",
        headers=headers,
        json={"name": "Duplicate Test"}
    )
    # Try to create again with same name
    response = requests.post(
        f"{BASE_URL}/projects/{project_id}/task-statuses",
        headers=headers,
        json={"name": "Duplicate Test"}
    )
    print(f"Status: {response.status_code}")
    print(f"Response: {response.text}")
    
    # Test 4: System status name conflict
    print("\n=== Test: System status name conflict ===")
    response = requests.post(
        f"{BASE_URL}/projects/{project_id}/task-statuses",
        headers=headers,
        json={"name": "In Progress"}
    )
    print(f"Status: {response.status_code}")
    print(f"Response: {response.text}")

def main():
    print("=" * 60)
    print("Testing Custom Task Status Creation")
    print("=" * 60)
    
    # Login
    token = login()
    if not token:
        print("Failed to login")
        return
    
    project_id = 1  # Use project ID 1 for testing
    
    # Get initial statuses
    print("\n" + "=" * 60)
    print("INITIAL STATE")
    print("=" * 60)
    get_all_statuses(token, project_id)
    
    # Create custom statuses
    print("\n" + "=" * 60)
    print("CREATING CUSTOM STATUSES")
    print("=" * 60)
    
    # Test 1: Create status without color (should auto-assign)
    create_custom_status(token, project_id, "Ready for Review")
    
    # Test 2: Create status with specific color
    create_custom_status(token, project_id, "On Hold", "#FFA500")
    
    # Test 3: Create another status (should get next color from palette)
    create_custom_status(token, project_id, "Blocked")
    
    # Get all statuses after creation
    print("\n" + "=" * 60)
    print("AFTER CREATION")
    print("=" * 60)
    get_all_statuses(token, project_id)
    
    # Test validation errors
    print("\n" + "=" * 60)
    print("VALIDATION TESTS")
    print("=" * 60)
    test_validation_errors(token, project_id)
    
    # Final state
    print("\n" + "=" * 60)
    print("FINAL STATE")
    print("=" * 60)
    get_all_statuses(token, project_id)

if __name__ == "__main__":
    main()
