from typing import Optional
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from app.services.chat_service import get_all_chats_service, get_chats_by_user, get_chats_by_id, process_chat_message_docs
from app.services.classifier_service import classificar_text, decidir_context, obtenir_context_i_ultima_pregunta
from app.core.dependencies import get_session_id
from app.core.security import verify_token

router = APIRouter()

class ChatRequest(BaseModel):
    chat_id: Optional[str] = None
    message: str

@router.get("/chats/me")
async def get_chats(
    session_id: str = Depends(get_session_id),
):
    if not session_id:
        raise HTTPException(status_code=401, detail="Usuari no identificat")

    chats = get_chats_by_user(session_id)
    chats = sorted(chats, key=lambda x: x.get('modified', ''), reverse=True)
    chats_list = []
    for chat in chats:
        chat["_id"] = str(chat["_id"])
        chats_list.append(chat)
    return chats_list

@router.get("/chats/all")
async def get_all_chats(user_data: dict = Depends(verify_token)):
    email = user_data.get("sub")
    if not email:
        raise HTTPException(status_code=401, detail="Usuari no identificat")
    chats = get_all_chats_service()
    chats = sorted(chats, key=lambda x: x.get('modified', ''), reverse=True)
    chats_list = []
    for chat in chats:
        chat["_id"] = str(chat["_id"])
        chats_list.append(chat)
    return chats_list
    

@router.get("/chats/{chat_id}")
async def get_chat(
    chat_id: str,
    session_id: str = Depends(get_session_id),
):
   
    if not session_id:
        raise HTTPException(status_code=401, detail="Usuari no identificat")

    chat = get_chats_by_id(session_id, chat_id)
    if not chat:
        raise HTTPException(status_code=404, detail="Xat no trobat")

    return chat

@router.post("/chats/rag/")
async def answer_questions_docs(request: ChatRequest, session_id: str = Depends(get_session_id), collection_name: str = None):  
    if request.chat_id:
        context_actiu, ultima_pregunta = obtenir_context_i_ultima_pregunta(request.chat_id)
    else:
        context_actiu = None
        ultima_pregunta = None

    if context_actiu is None:
        context_actiu = classificar_text(request.message)
    else:
        context_actiu = decidir_context(context_actiu, ultima_pregunta, request.message)      

    chat_id, bot_response, collection_name = process_chat_message_docs(session_id , request.chat_id, request.message, collection_name=context_actiu)
    return {"chat_id": chat_id, "response": bot_response, "collection_name": collection_name}
