"""Timeline business logic."""

from __future__ import annotations

from sqlalchemy import select
from sqlalchemy.orm import Session

from app.models.event import Event, EventPhase
from app.schemas.timeline import TimelineEventRead, TimelineGroupedRead
from app.services.engagements import get_engagement_by_id

TimelineResponse = list[TimelineEventRead] | TimelineGroupedRead


def get_timeline(
    db: Session,
    engagement_id: int,
    group_by_phase: bool = False,
) -> TimelineResponse:
    """Return timeline events sorted by ascending timestamp."""
    if get_engagement_by_id(db, engagement_id) is None:
        raise LookupError("engagement not found")

    events = db.scalars(
        select(Event)
        .where(Event.engagement_id == engagement_id)
        .order_by(Event.ts.asc(), Event.id.asc()),
    )

    timeline_events = [TimelineEventRead.model_validate(event) for event in events.all()]

    if not group_by_phase:
        return timeline_events

    grouped: dict[str, list[TimelineEventRead]] = {phase.value: [] for phase in EventPhase}
    for event in timeline_events:
        grouped[event.phase.value].append(event)

    return TimelineGroupedRead(
        engagement_id=engagement_id,
        phases=grouped,
    )
