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

# Configuration
BASE_URL = "http://localhost:8000"
PROJECT_ID = 1  # Adjust based on your test data

# Test credentials (adjust based on your test data)
LOGIN_EMAIL = "admin@vfx.com"
LOGIN_PASSWORD = "admin123"


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


def get_all_task_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
    )
    
    if response.status_code == 200:
        return response.json()
    else:
        print(f"Failed to get task statuses: {response.status_code}")
        print(response.text)
        return None


def create_custom_status(token, project_id, name, color=None):
    """Create a custom task status"""
    headers = {"Authorization": f"Bearer {token}"}
    data = {"name": name}
    if color:
        data["color"] = color
    
    response = requests.post(
        f"{BASE_URL}/projects/{project_id}/task-statuses",
        headers=headers,
        json=data
    )
    
    if response.status_code == 201:
        return response.json()
    else:
        print(f"Failed to create status: {response.status_code}")
        print(response.text)
        return None


def reorder_statuses(token, project_id, status_ids):
    """Reorder custom task statuses"""
    headers = {"Authorization": f"Bearer {token}"}
    data = {"status_ids": status_ids}
    
    response = requests.patch(
        f"{BASE_URL}/projects/{project_id}/task-statuses/reorder",
        headers=headers,
        json=data
    )
    
    if response.status_code == 200:
        return response.json()
    else:
        print(f"Failed to reorder statuses: {response.status_code}")
        print(response.text)
        return None


def main():
    print("=" * 60)
    print("Testing Custom Task Status Reordering")
    print("=" * 60)
    
    # Step 1: Login
    print("\n1. Logging in...")
    token = login()
    if not token:
        print("❌ Login failed")
        return
    print("✅ Login successful")
    
    # Step 2: Get current statuses
    print(f"\n2. Getting current task statuses for project {PROJECT_ID}...")
    statuses_response = get_all_task_statuses(token, PROJECT_ID)
    if not statuses_response:
        print("❌ Failed to get task statuses")
        return
    
    custom_statuses = statuses_response.get("statuses", [])
    print(f"✅ Found {len(custom_statuses)} custom statuses")
    
    # If no custom statuses exist, create some for testing
    if len(custom_statuses) < 3:
        print("\n3. Creating test custom statuses...")
        test_statuses = [
            ("Review", "#9333EA"),
            ("Blocked", "#DC2626"),
            ("Ready for Delivery", "#059669")
        ]
        
        for name, color in test_statuses:
            if len(custom_statuses) >= 3:
                break
            print(f"   Creating status: {name}")
            result = create_custom_status(token, PROJECT_ID, name, color)
            if result:
                custom_statuses = result.get("all_statuses", {}).get("statuses", [])
                print(f"   ✅ Created: {name}")
            else:
                print(f"   ❌ Failed to create: {name}")
        
        # Refresh statuses
        statuses_response = get_all_task_statuses(token, PROJECT_ID)
        custom_statuses = statuses_response.get("statuses", [])
    
    # Display current order
    print("\n4. Current status order:")
    for idx, status in enumerate(custom_statuses):
        print(f"   {idx + 1}. {status['name']} (ID: {status['id']}, Order: {status['order']})")
    
    if len(custom_statuses) < 2:
        print("\n⚠️  Need at least 2 custom statuses to test reordering")
        return
    
    # Step 3: Test reordering - reverse the order
    print("\n5. Testing reorder (reversing order)...")
    status_ids = [s['id'] for s in custom_statuses]
    reversed_ids = list(reversed(status_ids))
    
    print(f"   Original order: {status_ids}")
    print(f"   New order: {reversed_ids}")
    
    result = reorder_statuses(token, PROJECT_ID, reversed_ids)
    if not result:
        print("❌ Reorder failed")
        return
    
    print("✅ Reorder successful")
    
    # Step 4: Verify the new order
    print("\n6. Verifying new order...")
    statuses_response = get_all_task_statuses(token, PROJECT_ID)
    custom_statuses = statuses_response.get("statuses", [])
    
    print("   New status order:")
    for idx, status in enumerate(custom_statuses):
        print(f"   {idx + 1}. {status['name']} (ID: {status['id']}, Order: {status['order']})")
    
    # Verify order field matches position
    order_correct = all(status['order'] == idx for idx, status in enumerate(custom_statuses))
    if order_correct:
        print("✅ Order field correctly updated")
    else:
        print("❌ Order field mismatch")
    
    # Step 5: Test error cases
    print("\n7. Testing error cases...")
    
    # Test with missing status ID
    print("   a) Testing with missing status ID...")
    invalid_ids = reversed_ids[:-1]  # Remove last ID
    result = reorder_statuses(token, PROJECT_ID, invalid_ids)
    if result is None:
        print("   ✅ Correctly rejected incomplete status list")
    else:
        print("   ❌ Should have rejected incomplete status list")
    
    # Test with invalid status ID
    print("   b) Testing with invalid status ID...")
    invalid_ids = reversed_ids.copy()
    invalid_ids[0] = "invalid_id_12345"
    result = reorder_statuses(token, PROJECT_ID, invalid_ids)
    if result is None:
        print("   ✅ Correctly rejected invalid status ID")
    else:
        print("   ❌ Should have rejected invalid status ID")
    
    # Test with duplicate status IDs
    print("   c) Testing with duplicate status IDs...")
    duplicate_ids = [reversed_ids[0]] * len(reversed_ids)
    result = reorder_statuses(token, PROJECT_ID, duplicate_ids)
    if result is None:
        print("   ✅ Correctly rejected duplicate status IDs")
    else:
        print("   ❌ Should have rejected duplicate status IDs")
    
    print("\n" + "=" * 60)
    print("✅ All tests completed!")
    print("=" * 60)


if __name__ == "__main__":
    main()
