"""Creator endpoints for Chrysopedia API.""" import logging from typing import Annotated from fastapi import APIRouter, Depends, HTTPException, Query from sqlalchemy import func, select from sqlalchemy.ext.asyncio import AsyncSession from database import get_session from models import Creator, SourceVideo from schemas import CreatorDetail, CreatorRead logger = logging.getLogger("chrysopedia.creators") router = APIRouter(prefix="/creators", tags=["creators"]) @router.get("", response_model=list[CreatorRead]) async def list_creators( offset: Annotated[int, Query(ge=0)] = 0, limit: Annotated[int, Query(ge=1, le=100)] = 50, db: AsyncSession = Depends(get_session), ) -> list[CreatorRead]: """List all creators with pagination.""" stmt = select(Creator).order_by(Creator.name).offset(offset).limit(limit) result = await db.execute(stmt) creators = result.scalars().all() logger.debug("Listed %d creators (offset=%d, limit=%d)", len(creators), offset, limit) return [CreatorRead.model_validate(c) for c in creators] @router.get("/{slug}", response_model=CreatorDetail) async def get_creator( slug: str, db: AsyncSession = Depends(get_session), ) -> CreatorDetail: """Get a single creator by slug, including video count.""" stmt = select(Creator).where(Creator.slug == slug) result = await db.execute(stmt) creator = result.scalar_one_or_none() if creator is None: raise HTTPException(status_code=404, detail=f"Creator '{slug}' not found") # Count videos for this creator count_stmt = ( select(func.count()) .select_from(SourceVideo) .where(SourceVideo.creator_id == creator.id) ) count_result = await db.execute(count_stmt) video_count = count_result.scalar() or 0 creator_data = CreatorRead.model_validate(creator) return CreatorDetail(**creator_data.model_dump(), video_count=video_count)