from fastapi import APIRouter, HTTPException
from app.models.chat import ChatRequest, ChatResponse
from app.services.bedrock_service import BedrockService
from app.services.vector_service import VectorService
from app.services.assistant_service import AssistantService
from app.api.deps import CurrentUser, SessionDep

router = APIRouter()
assistant_service = AssistantService()
bedrock_service = assistant_service.bedrock_service
vector_service = assistant_service.vector_service

@router.post("/chat", response_model=ChatResponse)
async def chat(request: ChatRequest):
    try:
        # Obtener servicios relevantes
        relevant_services = vector_service.get_relevant_services(request.message)
        
        # Generar respuesta con Claude
        response = bedrock_service.generate_response_prueba(
            message=request.message,
            services=relevant_services
        )
        
        return ChatResponse(
            response=response,
            services=relevant_services
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e)) 


@router.post("/process-event", response_model=ChatResponse)
async def process_event(request: ChatRequest, session: SessionDep, current_user: CurrentUser):
    """
    Orquesta el flujo completo del asistente inteligente:
    1. Comprueba si falta información (Bedrock)
    2. Si falta, responde con la pregunta y espera input del usuario
    3. Si no falta, filtra servicios y vectoriza
    4. Llama a Bedrock para la recomendación final
    """
    try:
        # 1. Comprobación de información suficiente (Bedrock)
        needs_info, info_message = await assistant_service.check_info_needed(
            event=request.event,
            services=request.services,
            message=request.message,
            history=request.context  # si tienes historial de conversación
        )
        if needs_info:
            return {
                "needs_more_info": True,
                "message": info_message,
                "selected_services": []
            }

        # 2. Filtrado de servicios disponibles
        try:
            filtered_services = await assistant_service.filter_services(
                session=session,
                event=request.event,
                services=request.services,
                get_filtered=True
            )
        except Exception as e:
            raise HTTPException(status_code=400, detail=str(e))

        # 3. Vectorización y matching semántico
        relevant_services = await assistant_service.vectorize_and_match(
            session=session,
            user_message=request.message,
            services=filtered_services,
            event_data=request.event
        )

        # 4. Recomendación final (Bedrock)
        recommendation, selected_services = await assistant_service.final_recommendation(
            session=session,
            event=request.event,
            services=relevant_services,
            message=request.message,
            history=request.context
        )

        return {
            "needs_more_info": False,
            "message": recommendation,
            "selected_services": selected_services
    }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))