"""Timeline routes."""

from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.orm import Session

from app.core.db import get_db
from app.schemas.timeline import TimelineEventRead, TimelineGroupedRead
from app.services import timeline as timeline_service

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


@router.get("", response_model=list[TimelineEventRead] | TimelineGroupedRead)
def get_timeline(
    engagement_id: int | None = Query(default=None, ge=1),
    group_by_phase: bool = Query(default=False),
    db: Session = Depends(get_db),
) -> list[TimelineEventRead] | TimelineGroupedRead:
    """Return timeline data for one engagement."""
    if engagement_id is None:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="engagement_id is required",
        )

    try:
        return timeline_service.get_timeline(
            db=db,
            engagement_id=engagement_id,
            group_by_phase=group_by_phase,
        )
    except LookupError as exc:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
