"""
Manual test script for update custom task status endpoint
Run this with the backend server running
"""

import requests
import json

BASE_URL = "http://localhost:8000"

def print_section(title):
    print("\n" + "=" * 80)
    print(title)
    print("=" * 80)

def login():
    """Login and get token"""
    print("\n1. Logging in...")
    response = requests.post(
        f"{BASE_URL}/auth/login",
        json={"email": "admin@vfx.com", "password": "admin123"}
    )
    if response.status_code == 200:
        print("✅ Login successful")
        return response.json()["access_token"]
    else:
        print(f"❌ Login failed: {response.status_code}")
        print(response.text)
        return None

def create_test_status(token, project_id):
    """Create a test status"""
    print("\n2. Creating test status...")
    headers = {"Authorization": f"Bearer {token}"}
    response = requests.post(
        f"{BASE_URL}/projects/{project_id}/task-statuses",
        headers=headers,
        json={"name": "Test Status", "color": "#FF5733"}
    )
    if response.status_code == 201:
        status = response.json()["status"]
        print(f"✅ Created status: {status['name']} (ID: {status['id']})")
        return status['id']
    else:
        print(f"❌ Failed to create status: {response.status_code}")
        print(response.text)
        return None

def update_status_name(token, project_id, status_id):
    """Test updating status name"""
    print("\n3. Testing name update...")
    headers = {"Authorization": f"Bearer {token}"}
    response = requests.put(
        f"{BASE_URL}/projects/{project_id}/task-statuses/{status_id}",
        headers=headers,
        json={"name": "Updated Test Status"}
    )
    if response.status_code == 200:
        status = response.json()["status"]
        print(f"✅ Name updated: {status['name']}")
        return True
    else:
        print(f"❌ Failed to update name: {response.status_code}")
        print(response.text)
        return False

def update_status_color(token, project_id, status_id):
    """Test updating status color"""
    print("\n4. Testing color update...")
    headers = {"Authorization": f"Bearer {token}"}
    response = requests.put(
        f"{BASE_URL}/projects/{project_id}/task-statuses/{status_id}",
        headers=headers,
        json={"color": "#00FF00"}
    )
    if response.status_code == 200:
        status = response.json()["status"]
        print(f"✅ Color updated: {status['color']}")
        return True
    else:
        print(f"❌ Failed to update color: {response.status_code}")
        print(response.text)
        return False

def update_both(token, project_id, status_id):
    """Test updating both name and color"""
    print("\n5. Testing update of both name and color...")
    headers = {"Authorization": f"Bearer {token}"}
    response = requests.put(
        f"{BASE_URL}/projects/{project_id}/task-statuses/{status_id}",
        headers=headers,
        json={"name": "Final Status", "color": "#0000FF"}
    )
    if response.status_code == 200:
        status = response.json()["status"]
        print(f"✅ Both updated - Name: {status['name']}, Color: {status['color']}")
        return True
    else:
        print(f"❌ Failed to update both: {response.status_code}")
        print(response.text)
        return False

def test_duplicate_name(token, project_id, status_id):
    """Test duplicate name validation"""
    print("\n6. Testing duplicate name validation...")
    
    # Create another status
    headers = {"Authorization": f"Bearer {token}"}
    response = requests.post(
        f"{BASE_URL}/projects/{project_id}/task-statuses",
        headers=headers,
        json={"name": "Another Status"}
    )
    if response.status_code != 201:
        print(f"❌ Failed to create second status")
        return False
    
    # Try to update first status with duplicate name
    response = requests.put(
        f"{BASE_URL}/projects/{project_id}/task-statuses/{status_id}",
        headers=headers,
        json={"name": "Another Status"}
    )
    if response.status_code == 409:
        print(f"✅ Duplicate name correctly rejected")
        return True
    else:
        print(f"❌ Duplicate name was not rejected: {response.status_code}")
        return False

def test_system_name_conflict(token, project_id, status_id):
    """Test system status name conflict"""
    print("\n7. Testing system status name conflict...")
    headers = {"Authorization": f"Bearer {token}"}
    response = requests.put(
        f"{BASE_URL}/projects/{project_id}/task-statuses/{status_id}",
        headers=headers,
        json={"name": "In Progress"}
    )
    if response.status_code == 409:
        print(f"✅ System status name correctly rejected")
        return True
    else:
        print(f"❌ System status name was not rejected: {response.status_code}")
        return False

def test_set_default(token, project_id, status_id):
    """Test setting status as default"""
    print("\n8. Testing set as default...")
    headers = {"Authorization": f"Bearer {token}"}
    response = requests.put(
        f"{BASE_URL}/projects/{project_id}/task-statuses/{status_id}",
        headers=headers,
        json={"is_default": True}
    )
    if response.status_code == 200:
        result = response.json()
        status = result["status"]
        all_statuses = result["all_statuses"]
        
        if status["is_default"] and all_statuses["default_status_id"] == status_id:
            # Check only one default
            default_count = sum(1 for s in all_statuses["statuses"] if s["is_default"])
            if default_count == 1:
                print(f"✅ Status set as default, only one default exists")
                return True
            else:
                print(f"❌ Multiple defaults found: {default_count}")
                return False
        else:
            print(f"❌ Status not set as default correctly")
            return False
    else:
        print(f"❌ Failed to set as default: {response.status_code}")
        print(response.text)
        return False

def main():
    print_section("Manual Test for Custom Task Status Update Endpoint")
    
    token = login()
    if not token:
        return
    
    project_id = 1  # Assuming project 1 exists
    
    # Create test status
    status_id = create_test_status(token, project_id)
    if not status_id:
        return
    
    # Run tests
    tests_passed = 0
    tests_total = 7
    
    if update_status_name(token, project_id, status_id):
        tests_passed += 1
    
    if update_status_color(token, project_id, status_id):
        tests_passed += 1
    
    if update_both(token, project_id, status_id):
        tests_passed += 1
    
    if test_duplicate_name(token, project_id, status_id):
        tests_passed += 1
    
    if test_system_name_conflict(token, project_id, status_id):
        tests_passed += 1
    
    if test_set_default(token, project_id, status_id):
        tests_passed += 1
    
    # Test non-existent status
    print("\n9. Testing non-existent status...")
    headers = {"Authorization": f"Bearer {token}"}
    response = requests.put(
        f"{BASE_URL}/projects/{project_id}/task-statuses/nonexistent",
        headers=headers,
        json={"name": "Test"}
    )
    if response.status_code == 404:
        print(f"✅ Non-existent status correctly rejected")
        tests_passed += 1
    else:
        print(f"❌ Non-existent status was not rejected: {response.status_code}")
    
    # Summary
    print_section("Test Summary")
    print(f"\nTests passed: {tests_passed}/{tests_total}")
    
    if tests_passed == tests_total:
        print("\n✅ ALL TESTS PASSED!")
        print("\nImplementation verified:")
        print("  ✅ Status name update (Requirement 2.1)")
        print("  ✅ Status color update (Requirement 2.2)")
        print("  ✅ Default status management (Requirement 2.3, 5.2)")
        print("  ✅ Name uniqueness validation (Requirement 2.4)")
        print("  ✅ System status name conflict detection")
        print("  ✅ Only one default status at a time")
        print("  ✅ Non-existent status handling")
    else:
        print(f"\n❌ {tests_total - tests_passed} test(s) failed")

if __name__ == "__main__":
    main()
