import requests
from sqlmodel import Session, select
from database import engine
from models import Performance, Show, Song
from import_elgoose import fetch_json

BASE_URL = "https://elgoose.net/api/v2"

# Disable SQL echoing for this script to reduce noise
engine.echo = False

def fix_set_names():
    print("🔧 Fixing set names in database...")
    
    with Session(engine) as session:
        # Load maps (we need show_id and song_id mapping if we rely on API IDs... 
        # but API setlists endpoint returns show_id and song_id (El Goose IDs))
        # We need to match existing performances by show/song/position.
        
        # To avoid re-fetching ALL simple tables, let's just map on the fly or load needed.
        # Actually, simpler:
        # 1. Fetch setlists page.
        # 2. For each item, find corresponding Performance in DB using elgoose IDs?
        #    Wait, Performance table doesn't store El Goose IDs directly (no external_id column).
        #    It links to Show and Song. Show and Song *might* not strictly store external ID either (only slug/etc).
        #    But `import_elgoose.py` maps them.
        
        # We need to map El Goose Show ID -> local Show ID
        # We need to map El Goose Song ID -> local Song ID
        
        # This is tricky without storing external IDs.
        # However, we can fetch all shows and map via date? No, Shows might map via... 
        # Wait, how does `import_elgoose.py` map? 
        # distinct show_id map.
        
        print("Loading Show Map (by date + venue? No, we need external IDs)...")
        # Since we didn't save external IDs on Show/Song tables, we have to rebuild the map 
        # the same way import_elgoose does (fetching shows to get their IDs and matching to DB).
        # This is heavy.
        
        # ALTERNATIVE:
        # Just map by (Show Date, Song Title, Position)?
        # Show Date is in Show table. Song Title in Song table. Performance has position.
        # API setlist item has: showdate, songname, position, setnumber.
        # This is sufficient!
        
        page = 1
        updated_count = 0
        
        while True:
            print(f"  Fetching page {page}...", end="", flush=True)
            data = fetch_json("setlists", {"page": page})
            if not data:
                print(" Done.")
                break
                
            print(f" Loop {len(data)} items...", end="", flush=True)
            
            for item in data:
                show_date_str = item.get('showdate')
                song_name = item.get('songname')
                position = item.get('position')
                setnumber = item.get('setnumber', '1')
                
                if not show_date_str or not song_name:
                    continue
                    
                # Find DB records
                # Join Performance -> Show, Song
                db_perf = session.exec(
                    select(Performance)
                    .join(Show)
                    .join(Song)
                    .where(Show.date == show_date_str)
                    .where(Song.title == song_name)
                    .where(Performance.position == position)
                ).first()
                
                if db_perf:
                    # Logic to determine set name
                    set_val = str(setnumber) if setnumber is not None else '1'
                    
                    new_set_name = "Set 1"
                    if set_val.isdigit():
                        new_set_name = f"Set {set_val}"
                    elif set_val.lower() == 'e':
                        new_set_name = "Encore"
                    elif set_val.lower() == 'e2':
                        new_set_name = "Encore 2"
                    elif set_val.lower() == 's':
                        new_set_name = "Soundcheck"
                    else:
                        new_set_name = f"Set {set_val}"
                        
                    if db_perf.set_name != new_set_name:
                        db_perf.set_name = new_set_name
                        session.add(db_perf)
                        updated_count += 1
            
            session.commit()
            print(f" Committed (Total updated: {updated_count})")
            page += 1
            
            if page > 200: # Safety
                break

if __name__ == "__main__":
    fix_set_names()
