from fastapi import APIRouter, Depends, HTTPException, Query
from sqlmodel import Session, select
from typing import List, Optional
from database import get_session
from models import Artist, Song, Performance, Show, PerformanceArtist
from schemas import SongRead

router = APIRouter(prefix="/artists", tags=["artists"])

@router.get("/{slug}")
async def get_artist(slug: str, session: Session = Depends(get_session)):
    """Get artist details, covers, and guest appearances"""
    artist = session.exec(select(Artist).where(Artist.slug == slug)).first()
    if not artist:
        raise HTTPException(status_code=404, detail="Artist not found")
        
    # Get covers (Songs by this artist that Goose has played)
    covers = session.exec(
        select(Song)
        .where(Song.artist_id == artist.id)
        .order_by(Song.title)
    ).all()
    
    # Get guest appearances (Performances where this artist is linked)
    # This queries the PerformanceArtist link table
    guest_appearances = session.exec(
        select(Performance, Show)
        .join(PerformanceArtist, PerformanceArtist.performance_id == Performance.id)
        .join(Show, Performance.show_id == Show.id)
        .where(PerformanceArtist.artist_id == artist.id)
        .order_by(Show.date.desc())
    ).all()
    
    # Format guest appearances
    guest_spots = []
    for perf, show in guest_appearances:
        guest_spots.append({
            "date": show.date,
            "venue": show.venue.name if show.venue else "Unknown Venue",
            "city": f"{show.venue.city}, {show.venue.state}" if show.venue else "",
            "song_title": perf.song.title,
            "show_slug": show.slug,
            "song_slug": perf.song.slug
        })

    return {
        "artist": artist,
        "covers": covers,
        "guest_appearances": guest_spots
    }
