from typing import Annotated

from fastapi import APIRouter, Depends, HTTPException
from session_hub_fastapi.models.session_hub import MessageRow, SessionDetail, SessionRow

from session_hub_api.dependencies import get_query_api
from session_hub_api.mapping import message_row, session_detail, session_row
from session_hub_core.exceptions import SessionNotFoundError
from session_hub_core.query import QueryAPI

router = APIRouter(tags=["Sessions"])


@router.get("/api/sessions", response_model=list[SessionRow])
async def list_sessions(
    query_api: Annotated[QueryAPI, Depends(get_query_api)],
    tool: str | None = None,
    host: str | None = None,
    working_directory: str | None = None,
    limit: int = 50,
    offset: int = 0,
) -> list[SessionRow]:
    rows = await query_api.list_sessions(
        tool=tool,
        host=host,
        working_directory=working_directory,
        limit=limit,
        offset=offset,
    )
    return [session_row(row) for row in rows]


@router.get("/api/sessions/{host}/{tool}/{session_id}/messages", response_model=list[MessageRow])
async def get_messages(
    host: str,
    tool: str,
    session_id: str,
    query_api: Annotated[QueryAPI, Depends(get_query_api)],
) -> list[MessageRow]:
    try:
        detail = await query_api.get_session(host=host, tool=tool, session_id=session_id)
    except SessionNotFoundError as exc:
        raise HTTPException(status_code=404, detail=str(exc)) from exc
    return [message_row(message) for message in detail.messages]


@router.get("/api/sessions/{host}/{tool}/{session_id}", response_model=SessionDetail)
async def get_session(
    host: str,
    tool: str,
    session_id: str,
    query_api: Annotated[QueryAPI, Depends(get_query_api)],
) -> SessionDetail:
    try:
        detail = await query_api.get_session(host=host, tool=tool, session_id=session_id)
    except SessionNotFoundError as exc:
        raise HTTPException(status_code=404, detail=str(exc)) from exc
    return session_detail(detail)
