"""
Seed script to create common cross-band musicians.

These are musicians known for sitting in with multiple bands.
"""

from sqlmodel import Session, select
from database import engine
from models import Musician, Artist, BandMembership
import re


def generate_slug(name: str) -> str:
    """Generate URL-safe slug"""
    slug = name.lower()
    slug = re.sub(r'[^\w\s-]', '', slug)
    slug = re.sub(r'[\s_]+', '-', slug)
    return slug.strip('-')


# Notable jam scene musicians who appear across bands
CROSS_BAND_MUSICIANS = [
    # Grateful Dead / Dead Family
    {"name": "Bob Weir", "primary_instrument": "Guitar", "bands": ["grateful-dead", "dead-and-company"]},
    {"name": "Mickey Hart", "primary_instrument": "Drums", "bands": ["grateful-dead", "dead-and-company"]},
    {"name": "Bill Kreutzmann", "primary_instrument": "Drums", "bands": ["grateful-dead", "dead-and-company"]},
    {"name": "John Mayer", "primary_instrument": "Guitar", "bands": ["dead-and-company"]},
    {"name": "Oteil Burbridge", "primary_instrument": "Bass", "bands": ["dead-and-company"]},
    {"name": "Jeff Chimenti", "primary_instrument": "Keyboards", "bands": ["dead-and-company"]},
    
    # Goose
    {"name": "Rick Mitarotonda", "primary_instrument": "Guitar, Vocals", "bands": ["goose"]},
    {"name": "Peter Anspach", "primary_instrument": "Keyboards, Guitar", "bands": ["goose"]},
    {"name": "Trevor Weekz", "primary_instrument": "Bass", "bands": ["goose"]},
    {"name": "Ben Atkind", "primary_instrument": "Drums", "bands": ["goose"]},
    {"name": "Jeff Arevalo", "primary_instrument": "Percussion", "bands": ["goose"]},
    
    # Phish
    {"name": "Trey Anastasio", "primary_instrument": "Guitar", "bands": ["phish"]},
    {"name": "Page McConnell", "primary_instrument": "Keyboards", "bands": ["phish"]},
    {"name": "Mike Gordon", "primary_instrument": "Bass", "bands": ["phish"]},
    {"name": "Jon Fishman", "primary_instrument": "Drums", "bands": ["phish"]},
    
    # Billy Strings
    {"name": "Billy Strings", "primary_instrument": "Guitar, Vocals", "bands": ["billy-strings"]},
    {"name": "Billy Failing", "primary_instrument": "Banjo", "bands": ["billy-strings"]},
    {"name": "Royal Masat", "primary_instrument": "Bass", "bands": ["billy-strings"]},
    {"name": "Jarrod Walker", "primary_instrument": "Mandolin", "bands": ["billy-strings"]},
    
    # Cross-band sit-in regulars
    {"name": "Marcus King", "primary_instrument": "Guitar, Vocals", "bands": []},
    {"name": "Pigeons Playing Ping Pong", "primary_instrument": "Funk", "bands": []},
    {"name": "Karina Rykman", "primary_instrument": "Bass, Vocals", "bands": []},
]


def seed_musicians():
    """Create musicians if they don't exist"""
    print("Seeding musicians...\n")
    
    with Session(engine) as session:
        created = 0
        
        for m in CROSS_BAND_MUSICIANS:
            slug = generate_slug(m["name"])
            
            existing = session.exec(
                select(Musician).where(Musician.slug == slug)
            ).first()
            
            if existing:
                print(f"  Exists: {m['name']}")
                musician = existing
            else:
                musician = Musician(
                    name=m["name"],
                    slug=slug,
                    primary_instrument=m["primary_instrument"]
                )
                session.add(musician)
                session.commit()
                session.refresh(musician)
                created += 1
                print(f"  Created: {m['name']}")
            
            # Create band memberships
            for band_slug in m.get("bands", []):
                # Find vertical by slug to get artist
                from models import Vertical
                vertical = session.exec(
                    select(Vertical).where(Vertical.slug == band_slug)
                ).first()
                
                if vertical and vertical.primary_artist_id:
                    # Check if membership exists
                    existing_membership = session.exec(
                        select(BandMembership)
                        .where(BandMembership.musician_id == musician.id)
                        .where(BandMembership.artist_id == vertical.primary_artist_id)
                    ).first()
                    
                    if not existing_membership:
                        membership = BandMembership(
                            musician_id=musician.id,
                            artist_id=vertical.primary_artist_id,
                            role=m["primary_instrument"]
                        )
                        session.add(membership)
                        print(f"    -> Added to {band_slug}")
        
        session.commit()
        print(f"\nCreated {created} new musicians")


if __name__ == "__main__":
    seed_musicians()
