"""
Sync original_artist data from elgoose.net API to local Songs.
Then create Artist records and link Songs.
"""
import httpx
from sqlmodel import Session, select
from database import engine
from models import Song, Artist
from slugify import generate_slug as slugify

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

def fetch_all_songs():
    """Fetch all songs from elgoose API"""
    url = f"{BASE_URL}/songs"
    print(f"Fetching songs from {url}...")
    response = httpx.get(url, timeout=30)
    response.raise_for_status()
    data = response.json()
    return data.get("data", [])

def sync_original_artists():
    """Sync original_artist from API to local Songs"""
    api_songs = fetch_all_songs()
    print(f"Fetched {len(api_songs)} songs from API")
    
    with Session(engine) as session:
        updated = 0
        
        for api_song in api_songs:
            # Skip originals (isoriginal=1 means Goose original)
            if api_song.get("isoriginal") == 1:
                continue
                
            slug = api_song.get("slug")
            original_artist = api_song.get("original_artist")
            
            if not slug or not original_artist or original_artist == "Goose":
                continue
            
            # Find matching local Song by slug
            local_song = session.exec(select(Song).where(Song.slug == slug)).first()
            if local_song and not local_song.original_artist:
                local_song.original_artist = original_artist
                session.add(local_song)
                updated += 1
                print(f"Updated: {local_song.title} -> {original_artist}")
        
        session.commit()
        print(f"\nSynced original_artist for {updated} cover songs")
        return updated

def create_artist_records():
    """Create Artist records from original_artist strings and link Songs"""
    with Session(engine) as session:
        songs = session.exec(select(Song).where(Song.original_artist != None)).all()
        print(f"Found {len(songs)} songs with original_artist")
        
        created = 0
        linked = 0
        
        for song in songs:
            if not song.original_artist or song.artist_id:
                continue
            
            artist_name = song.original_artist.strip()
            if not artist_name or artist_name == "Goose":
                continue
            
            artist_slug = slugify(artist_name)
            
            # Find or Create Artist
            artist = session.exec(select(Artist).where(Artist.slug == artist_slug)).first()
            if not artist:
                artist = Artist(name=artist_name, slug=artist_slug)
                session.add(artist)
                session.commit()
                session.refresh(artist)
                created += 1
                print(f"Created Artist: {artist_name}")
            
            # Link Song
            song.artist_id = artist.id
            session.add(song)
            linked += 1
        
        session.commit()
        print(f"\nCreated {created} artists, linked {linked} songs")
        return created, linked

if __name__ == "__main__":
    print("=" * 50)
    print("ARTIST SYNC FROM ELGOOSE API")
    print("=" * 50)
    
    # Step 1: Sync original_artist strings
    updated_count = sync_original_artists()
    
    # Step 2: Create Artist records and link
    created, linked = create_artist_records()
    
    print("=" * 50)
    print(f"COMPLETE: Updated {updated_count} songs, Created {created} artists, Linked {linked} songs")
    print("=" * 50)
