from typing import List
from fastapi import APIRouter, Depends, Query
from sqlmodel import Session, select, func
from database import get_session
from models import Song, Performance

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

@router.get("/top-songs")
def get_top_songs(
    limit: int = Query(default=10, le=50),
    session: Session = Depends(get_session)
):
    """Get top songs by number of performances"""
    query = (
        select(Song.id, Song.title, func.count(Performance.id).label("performance_count"))
        .join(Performance, Song.id == Performance.song_id)
        .group_by(Song.id, Song.title)
        .order_by(func.count(Performance.id).desc())
        .limit(limit)
    )
    results = session.exec(query).all()
    return [
        {"id": r[0], "title": r[1], "performance_count": r[2]}
        for r in results
    ]
