"""Database migration utilities."""

import sqlite3
from pathlib import Path


def migrate_to_v2(db_path: str):
    """Migrate database from v1 (desc1, desc2) to v2 (description)."""
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()
    
    try:
        # Check if we need to migrate
        cursor.execute("PRAGMA table_info(cards)")
        columns = [col[1] for col in cursor.fetchall()]
        
        if 'description' in columns:
            print("Database already migrated to v2")
            return
        
        if 'desc1' not in columns:
            print("Database is already in correct format")
            return
        
        print("Migrating database to v2...")
        
        # Create new table with description field
        cursor.execute("""
            CREATE TABLE cards_new (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                title TEXT NOT NULL,
                description TEXT,
                created_at TIMESTAMP NOT NULL,
                updated_at TIMESTAMP NOT NULL
            )
        """)
        
        # Migrate data: combine desc1 and desc2 into description
        cursor.execute("""
            INSERT INTO cards_new (id, title, description, created_at, updated_at)
            SELECT 
                id, 
                title,
                CASE 
                    WHEN desc1 IS NOT NULL AND desc2 IS NOT NULL THEN desc1 || '\n' || desc2
                    WHEN desc1 IS NOT NULL THEN desc1
                    WHEN desc2 IS NOT NULL THEN desc2
                    ELSE NULL
                END as description,
                created_at,
                updated_at
            FROM cards
        """)
        
        # Drop old table and rename new one
        cursor.execute("DROP TABLE cards")
        cursor.execute("ALTER TABLE cards_new RENAME TO cards")
        
        # Create index
        cursor.execute("CREATE INDEX ix_cards_title ON cards (title)")
        cursor.execute("CREATE INDEX ix_cards_id ON cards (id)")
        
        conn.commit()
        print("Migration completed successfully!")
        
    except Exception as e:
        conn.rollback()
        print(f"Migration failed: {e}")
        raise
    finally:
        conn.close()


def check_and_migrate(db_path: str):
    """Check database version and migrate if needed."""
    if not Path(db_path).exists():
        # New database, no migration needed
        return
    
    try:
        migrate_to_v2(db_path)
    except Exception as e:
        print(f"Warning: Could not migrate database: {e}")
        print("You may need to delete the old database and start fresh.")
