"""Router for AI Chat Assistant endpoint."""

from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from sqlalchemy.ext.asyncio import AsyncSession

from app.core.database import get_db
from app.dependencies import get_current_user
from app.models.user import User

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


class ChatRequest(BaseModel):
    message: str
    spbu_id: int
    conversation_history: list[dict] | None = None


class ChatResponse(BaseModel):
    response: str
    tools_used: list[str] = []
    provider: str = ""


@router.post("", response_model=ChatResponse)
async def chat(
    data: ChatRequest,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user),
) -> ChatResponse:
    """Send a message to the AI assistant and get a response."""
    from app.assistant.service import chat as assistant_chat

    try:
        result = await assistant_chat(
            db,
            spbu_id=data.spbu_id,
            user_message=data.message,
            conversation_history=data.conversation_history,
        )
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))

    return ChatResponse(**result)
