package com.pablotj.ia.chat.boot.application.usecase;

import com.pablotj.ia.chat.boot.application.prompt.PromptBuilder;
import com.pablotj.ia.chat.boot.application.prompt.PromptTemplates;
import com.pablotj.ia.chat.boot.application.session.ChatSessionManager;
import com.pablotj.ia.chat.boot.domain.model.ChatMessage;
import com.pablotj.ia.chat.boot.infraestructure.llm.LlmModelClient;
import java.util.Date;
import java.util.List;
import org.springframework.stereotype.Component;

@Component
public class ChatUseCase {

    private static final String ATTR_ROLE_BOT = "bot";
    private static final String ATTR_ROLE_USER = "user";

    private final LlmModelClient llmModelClient;
    private final ChatSessionManager sessionManager;

    public ChatUseCase(LlmModelClient llmModelClient,
                       ChatSessionManager sessionManager) {
        this.llmModelClient = llmModelClient;
        this.sessionManager = sessionManager;
    }

    public List<ChatMessage> getMessages(String chatId) {
        return sessionManager.getMessages(chatId);
    }

    public ChatMessage processUserPrompt(String prompt, String chatId) {
        List<ChatMessage> messages = sessionManager.getMessages(chatId);
        messages.add(new ChatMessage(chatId, ATTR_ROLE_USER, prompt, new Date()));

        PromptBuilder builder = new PromptBuilder(PromptTemplates.getDefault());

        for (ChatMessage message : messages) {
            if (ATTR_ROLE_USER.equals(message.role())) {
                builder.user(message.text());
            } else if (ATTR_ROLE_BOT.equals(message.role())) {
                builder.assistant(message.text());
            }
        }

        String result = llmModelClient.generate(builder.build());
        ChatMessage reply = new ChatMessage(chatId, ATTR_ROLE_BOT, result, new Date());
        messages.add(reply);
        sessionManager.setMessages(chatId, messages);
        return reply;
    }
}
