from fastapi import APIRouter, Depends, HTTPException
from typing import List, Optional
from ...models.chat import ChatRequest, ChatResponse, ChatHistory
from ...services.chat_service import ChatService
from ...core.deps import get_current_user
from ...models.user import User

router = APIRouter()
chat_service = ChatService()

@router.post("/chat", response_model=ChatResponse)
async def chat(
    request: ChatRequest,
    current_user: User = Depends(get_current_user)
):
    """
    Procesa un mensaje del usuario y devuelve una respuesta del asistente.
    """
    try:
        # Verificar que el usuario actual coincide con el user_id en la solicitud
        if str(current_user.id) != request.user_id:
            raise HTTPException(status_code=403, detail="No autorizado para usar este chat")

        response = chat_service.process_message(request)
        return response
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/chat/history/{event_id}", response_model=ChatHistory)
async def get_chat_history(
    event_id: Optional[str],
    current_user: User = Depends(get_current_user)
):
    """
    Obtiene el historial de chat para un usuario y evento específicos.
    """
    try:
        chat_history = chat_service.get_chat_history(str(current_user.id), event_id)
        return chat_history
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.delete("/chat/history/{event_id}")
async def clear_chat_history(
    event_id: Optional[str],
    current_user: User = Depends(get_current_user)
):
    """
    Limpia el historial de chat para un usuario y evento específicos.
    """
    try:
        key = f"{current_user.id}_{event_id}" if event_id else str(current_user.id)
        if key in chat_service.chat_histories:
            del chat_service.chat_histories[key]
        return {"message": "Historial de chat eliminado correctamente"}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e)) 