"""Source video endpoints for Chrysopedia API."""

import logging
from typing import Annotated

from fastapi import APIRouter, Depends, Query
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from database import get_session
from models import SourceVideo
from schemas import SourceVideoRead

logger = logging.getLogger("chrysopedia.videos")

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


@router.get("", response_model=list[SourceVideoRead])
async def list_videos(
    offset: Annotated[int, Query(ge=0)] = 0,
    limit: Annotated[int, Query(ge=1, le=100)] = 50,
    creator_id: str | None = None,
    db: AsyncSession = Depends(get_session),
) -> list[SourceVideoRead]:
    """List source videos with optional filtering by creator."""
    stmt = select(SourceVideo).order_by(SourceVideo.created_at.desc())

    if creator_id:
        stmt = stmt.where(SourceVideo.creator_id == creator_id)

    stmt = stmt.offset(offset).limit(limit)
    result = await db.execute(stmt)
    videos = result.scalars().all()
    logger.debug("Listed %d videos (offset=%d, limit=%d)", len(videos), offset, limit)
    return [SourceVideoRead.model_validate(v) for v in videos]
