"""REST endpoint for sending a message to an agent (non-streaming)."""

from typing import Annotated

from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel

from navi.api.deps import get_agent
from navi.core import Agent
from navi.exceptions import MaxIterationsReached, NaviError, SessionNotFound

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


class SendMessageRequest(BaseModel):
    content: str


@router.post("/{session_id}/messages")
async def send_message(
    session_id: str,
    body: SendMessageRequest,
    agent: Annotated[Agent, Depends(get_agent)],
) -> dict:
    try:
        reply = await agent.run(session_id, body.content)
        return {"role": "assistant", "content": reply}
    except SessionNotFound:
        raise HTTPException(status_code=404, detail="Session not found")
    except MaxIterationsReached as e:
        raise HTTPException(status_code=500, detail=str(e))
    except NaviError as e:
        raise HTTPException(status_code=500, detail=str(e))
