"""
Test script for task status endpoints with custom statuses
"""
import requests
import json
from sqlalchemy.orm.attributes import flag_modified

BASE_URL = "http://localhost:8000"

def setup_custom_statuses():
    """Add custom statuses to a project for testing"""
    from database import SessionLocal
    from models.project import Project
    
    db = SessionLocal()
    
    # Get first project
    project = db.query(Project).first()
    if not project:
        print("❌ No project found")
        db.close()
        return None
    
    # Add custom statuses
    custom_statuses = [
        {
            "id": "custom_review",
            "name": "In Review",
            "color": "#8B5CF6",
            "order": 0,
            "is_default": False
        },
        {
            "id": "custom_blocked",
            "name": "Blocked",
            "color": "#DC2626",
            "order": 1,
            "is_default": False
        },
        {
            "id": "custom_ready",
            "name": "Ready for Delivery",
            "color": "#059669",
            "order": 2,
            "is_default": True  # Set as default
        }
    ]
    
    project.custom_task_statuses = custom_statuses
    flag_modified(project, 'custom_task_statuses')
    
    project_id = project.id
    
    db.commit()
    db.close()
    
    print(f"✅ Added {len(custom_statuses)} custom statuses to project {project_id}")
    return project_id


def test_get_all_task_statuses_with_custom():
    """Test getting all task statuses including custom ones"""
    
    # Setup custom statuses
    project_id = setup_custom_statuses()
    if not project_id:
        return
    
    # Login to get a token
    login_response = requests.post(
        f"{BASE_URL}/auth/login",
        json={
            "email": "admin@vfx.com",
            "password": "admin123"
        }
    )
    
    if login_response.status_code != 200:
        print(f"❌ Login failed: {login_response.status_code}")
        print(login_response.text)
        return
    
    token = login_response.json()["access_token"]
    headers = {"Authorization": f"Bearer {token}"}
    
    print("✅ Login successful")
    
    # Test GET /projects/{project_id}/task-statuses
    print(f"\n--- Testing GET /projects/{project_id}/task-statuses ---")
    response = requests.get(
        f"{BASE_URL}/projects/{project_id}/task-statuses",
        headers=headers
    )
    
    print(f"Status Code: {response.status_code}")
    
    if response.status_code == 200:
        data = response.json()
        print("✅ Successfully retrieved task statuses")
        print(f"\nResponse:")
        print(json.dumps(data, indent=2))
        
        # Validate response structure
        assert "statuses" in data, "Missing 'statuses' field"
        assert "system_statuses" in data, "Missing 'system_statuses' field"
        assert "default_status_id" in data, "Missing 'default_status_id' field"
        
        print(f"\n✅ System statuses count: {len(data['system_statuses'])}")
        print(f"✅ Custom statuses count: {len(data['statuses'])}")
        print(f"✅ Default status ID: {data['default_status_id']}")
        
        # Verify custom statuses
        assert len(data['statuses']) == 3, f"Expected 3 custom statuses, got {len(data['statuses'])}"
        print("✅ Correct number of custom statuses")
        
        # Verify default status is custom
        assert data['default_status_id'] == "custom_ready", f"Expected default to be 'custom_ready', got {data['default_status_id']}"
        print("✅ Default status correctly set to custom status")
        
        # Verify custom status structure
        for status in data['statuses']:
            assert "id" in status, f"Custom status missing 'id': {status}"
            assert "name" in status, f"Custom status missing 'name': {status}"
            assert "color" in status, f"Custom status missing 'color': {status}"
            assert "order" in status, f"Custom status missing 'order': {status}"
            assert "is_default" in status, f"Custom status missing 'is_default': {status}"
            print(f"✅ Custom status '{status['name']}' has all required fields")
        
        print("\n✅ All tests passed!")
        
    else:
        print(f"❌ Failed to get task statuses")
        print(response.text)


if __name__ == "__main__":
    test_get_all_task_statuses_with_custom()
