import datetime
import json
from collections.abc import Iterable

from folkugat_web.dal.sql import get_connection
from folkugat_web.dal.sql.sessions import playlists as session_playlists
from folkugat_web.model.playlists import PlaylistType
from folkugat_web.services import sessions as sessions_service
from folkugat_web.dal.sql.playlists import write as playlists_write

def main():
    """Main migration function."""
    with get_connection() as con:
        cur = con.cursor()
        query = """ SELECT 
                    sp.playlist_id,
                    sp.session_id,
                    s.date,
                    sp.playlist_type,
                    p.name as current_name
                FROM session_playlists sp
                JOIN sessions s ON sp.session_id = s.id
                JOIN playlists p ON sp.playlist_id = p.id
                WHERE p.name IS NULL OR p.name = ''
                ORDER BY sp.session_id, sp.playlist_type """
        _ = cur.execute(query)
        rows = cur.fetchall()
        
        if not rows:
            print("No session playlists need renaming.")
            return
        
        updated_count = 0
        for row in rows:
            playlist_id, session_id, session_date, playlist_type, current_name = row
            
            # Parse session date properly
            session_date = sessions_service.get_date_names(
                datetime.date.fromisoformat(session_date)
            )
            
            # Generate proper name based on playlist type
            if playlist_type == PlaylistType.SESSION_SETLIST.value:
                new_name = f"Sessió del {session_date.day} de {session_date.month_name} de {session_date.year}"
            elif playlist_type == PlaylistType.SESSION_SLOWJAM.value:
                new_name = f"Slow Jam del {session_date.day} de {session_date.month_name} de {session_date.year}"
            else:
                print(f"Unknown playlist type {playlist_type} for playlist {playlist_id}")
                continue
            
            # Update the playlist name using existing function
            playlists_write.update_playlist_name(
                playlist_id=playlist_id,
                name=new_name,
                con=con
            )
            
            current_name_display = current_name or "None"
            print(
                f"Updated playlist {playlist_id} (session {session_id}) "
                f"from '{current_name_display}' to '{new_name}'"
            )
            updated_count += 1
        
        con.commit()
        print(f"Migration completed! Updated {updated_count} playlist names.")
        print("DONE!")


if __name__ == "__main__":
    main()