package ai.decompile.ai.service;

import ai.decompile.ai.model.entity.ChatMessage;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

@Component
@ConditionalOnProperty(name = "app.ai.enabled", havingValue = "true", matchIfMissing = true)
public class ChatMessageConverter {

  @Value("${app.ai.chat.max-history-messages:20}")
  private int maxHistoryMessages;

  public List<Message> buildMessageList(
      String systemPrompt, List<ChatMessage> historyMessages, String userMessageContent) {
    var messages = new ArrayList<Message>();
    messages.add(new SystemMessage(systemPrompt));

    for (var histMsg : historyMessages) {
      if ("USER".equals(histMsg.getRole())) {
        messages.add(new UserMessage(histMsg.getContent()));
      } else {
        messages.add(new AssistantMessage(histMsg.getContent()));
      }
    }

    messages.add(new UserMessage(userMessageContent));
    return messages;
  }

  public List<ChatMessage> getRecentHistoryExcludingLastMessage(List<ChatMessage> messages) {
    if (messages.isEmpty()) {
      return Collections.emptyList();
    }

    var msgList = new ArrayList<>(messages);
    msgList.removeLast();
    if (msgList.size() > maxHistoryMessages) {
      return msgList.subList(msgList.size() - maxHistoryMessages, msgList.size());
    }

    return msgList;
  }
}
