"""
Migration script to create Musician, BandMembership, and PerformanceGuest tables.
"""
from sqlmodel import Session, text
from database import engine

def migrate_musicians():
    with Session(engine) as session:
        print("Running Musicians Migration...")
        
        # Create Musician table
        try:
            session.exec(text("""
                CREATE TABLE IF NOT EXISTS musician (
                    id SERIAL PRIMARY KEY,
                    name VARCHAR NOT NULL,
                    slug VARCHAR UNIQUE NOT NULL,
                    bio TEXT,
                    image_url VARCHAR,
                    primary_instrument VARCHAR,
                    notes TEXT
                )
            """))
            session.exec(text("CREATE INDEX IF NOT EXISTS idx_musician_name ON musician(name)"))
            session.exec(text("CREATE INDEX IF NOT EXISTS idx_musician_slug ON musician(slug)"))
            print("Created musician table")
        except Exception as e:
            print(f"musician table error: {e}")
            session.rollback()
        
        # Create BandMembership table
        try:
            session.exec(text("""
                CREATE TABLE IF NOT EXISTS bandmembership (
                    id SERIAL PRIMARY KEY,
                    musician_id INTEGER NOT NULL REFERENCES musician(id),
                    artist_id INTEGER NOT NULL REFERENCES artist(id),
                    role VARCHAR,
                    start_date TIMESTAMP,
                    end_date TIMESTAMP,
                    notes TEXT
                )
            """))
            print("Created bandmembership table")
        except Exception as e:
            print(f"bandmembership table error: {e}")
            session.rollback()
        
        # Create PerformanceGuest table
        try:
            session.exec(text("""
                CREATE TABLE IF NOT EXISTS performanceguest (
                    id SERIAL PRIMARY KEY,
                    performance_id INTEGER NOT NULL REFERENCES performance(id),
                    musician_id INTEGER NOT NULL REFERENCES musician(id),
                    instrument VARCHAR,
                    notes TEXT
                )
            """))
            print("Created performanceguest table")
        except Exception as e:
            print(f"performanceguest table error: {e}")
            session.rollback()
        
        session.commit()
        print("Musicians Migration Complete!")

if __name__ == "__main__":
    migrate_musicians()
