from sqlmodel import Session, create_engine, select
import os
from models import Show, Song, Venue, Performance, Tour
from slugify import generate_slug, generate_show_slug, generate_performance_slug

# Use environment variable or default to local sqlite for testing
DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///./database.db")
engine = create_engine(DATABASE_URL)

def fix_numeric_slugs():
    with Session(engine) as session:
        # 1. Songs
        songs = session.exec(select(Song)).all()
        for song in songs:
            if song.slug and song.slug.isdigit():
                old_slug = song.slug
                new_slug = generate_slug(song.title)
                # Check for collisions
                base_slug = new_slug
                counter = 1
                while session.exec(select(Song).where(Song.slug == new_slug).where(Song.id != song.id)).first():
                    new_slug = f"{base_slug}-{counter}"
                    counter += 1
                
                print(f"Updating Song slug: {old_slug} -> {new_slug}")
                song.slug = new_slug
                session.add(song)

        # 2. Venues
        venues = session.exec(select(Venue)).all()
        for venue in venues:
            if venue.slug and venue.slug.isdigit():
                old_slug = venue.slug
                new_slug = generate_slug(venue.name)
                # Check for collisions
                base_slug = new_slug
                counter = 1
                while session.exec(select(Venue).where(Venue.slug == new_slug).where(Venue.id != venue.id)).first():
                    new_slug = f"{base_slug}-{counter}"
                    counter += 1
                
                print(f"Updating Venue slug: {old_slug} -> {new_slug}")
                venue.slug = new_slug
                session.add(venue)

        # 3. Shows
        shows = session.exec(select(Show)).all()
        for show in shows:
            if show.slug and show.slug.isdigit():
                old_slug = show.slug
                venue_name = show.venue.name if (show.venue) else "unknown"
                new_slug = generate_show_slug(show.date.strftime("%Y-%m-%d"), venue_name)
                
                # Check for collisions
                base_slug = new_slug
                counter = 1
                while session.exec(select(Show).where(Show.slug == new_slug).where(Show.id != show.id)).first():
                    new_slug = f"{base_slug}-{counter}"
                    counter += 1
                
                print(f"Updating Show slug: {old_slug} -> {new_slug}")
                show.slug = new_slug
                session.add(show)
        
        # 4. Performances (checking just in case)
        performances = session.exec(select(Performance)).all()
        for perf in performances:
            if perf.slug and perf.slug.isdigit():
                old_slug = perf.slug
                song_title = perf.song.title if perf.song else "unknown"
                show_date = perf.show.date.strftime("%Y-%m-%d") if perf.show else "unknown"
                new_slug = generate_performance_slug(song_title, show_date)
                
                # Check for collisions
                base_slug = new_slug
                counter = 1
                while session.exec(select(Performance).where(Performance.slug == new_slug).where(Performance.id != perf.id)).first():
                    new_slug = f"{base_slug}-{counter}"
                    counter += 1
                
                print(f"Updating Performance slug: {old_slug} -> {new_slug}")
                perf.slug = new_slug
                session.add(perf)

        session.commit()
        print("Slug fixation complete.")

if __name__ == "__main__":
    fix_numeric_slugs()
