"""
Test script to verify custom task status migration
"""
import sqlite3
from pathlib import Path

DB_PATH = Path(__file__).parent / "vfx_project_management.db"


def test_migration():
    """Verify the migration was successful"""
    conn = sqlite3.connect(DB_PATH)
    cursor = conn.cursor()
    
    try:
        print("Testing custom task status migration...")
        print()
        
        # Test 1: Verify custom_task_statuses column exists in projects table
        cursor.execute("PRAGMA table_info(projects)")
        columns = [col[1] for col in cursor.fetchall()]
        assert 'custom_task_statuses' in columns, "custom_task_statuses column not found in projects table"
        print("✓ Test 1 passed: custom_task_statuses column exists in projects table")
        
        # Test 2: Verify task status column is TEXT type
        cursor.execute("PRAGMA table_info(tasks)")
        task_columns = {col[1]: col[2] for col in cursor.fetchall()}
        assert 'status' in task_columns, "status column not found in tasks table"
        print(f"✓ Test 2 passed: status column exists in tasks table (type: {task_columns['status']})")
        
        # Test 3: Verify all task statuses are lowercase strings
        cursor.execute("SELECT DISTINCT status FROM tasks")
        statuses = [row[0] for row in cursor.fetchall()]
        lowercase_statuses = ['not_started', 'in_progress', 'submitted', 'approved', 'retake']
        for status in statuses:
            assert status in lowercase_statuses, f"Invalid status found: {status}"
        print(f"✓ Test 3 passed: All task statuses are valid lowercase strings: {statuses}")
        
        # Test 4: Verify custom_task_statuses is initialized as empty array
        cursor.execute("SELECT custom_task_statuses FROM projects LIMIT 1")
        result = cursor.fetchone()
        if result:
            custom_statuses = result[0]
            assert custom_statuses == '[]', f"Expected empty array, got: {custom_statuses}"
            print(f"✓ Test 4 passed: custom_task_statuses initialized as empty array")
        else:
            print("⚠ Test 4 skipped: No projects in database")
        
        # Test 5: Count tasks by status
        cursor.execute("""
            SELECT status, COUNT(*) as count 
            FROM tasks 
            GROUP BY status 
            ORDER BY count DESC
        """)
        status_counts = cursor.fetchall()
        print()
        print("Task status distribution:")
        for status, count in status_counts:
            print(f"  - {status}: {count} tasks")
        
        print()
        print("✅ All tests passed! Migration successful.")
        
    except AssertionError as e:
        print(f"❌ Test failed: {e}")
        return False
    except Exception as e:
        print(f"❌ Error during testing: {e}")
        return False
    finally:
        conn.close()
    
    return True


if __name__ == "__main__":
    success = test_migration()
    exit(0 if success else 1)
