import { ArrayUtils } from "@imengyu/imengyu-utils";
import { ChatMessage as ChatMessageModel } from "../model/Message";
import { reactive, type Ref } from "vue";
import type OpenAI from "openai";


export function useMessages(messages: Ref<ChatMessageModel[]>) {

  function addMessage(message: ChatMessageModel) {
    const wrappedMessage = reactive(message);
    messages.value.push(wrappedMessage as ChatMessageModel);
    return wrappedMessage as ChatMessageModel;
  }
  function removeMessage(message: ChatMessageModel) {
    ArrayUtils.removeAt(messages.value, messages.value.findIndex(m => m.id === message.id));
  }
  function findMessage(id: number) {
    return messages.value.find((m) => m.id === id) as ChatMessageModel | undefined;
  }
  function updateMessage(id: number, update: (message: ChatMessageModel) => void) {
    const message = findMessage(id);
    if (message) {
      update(message);
    } else {
      console.warn(`Message with id ${id} not found`);
    }
  }
  function clearMessages() {
    messages.value = [];
  }

  return {
    addMessage,
    removeMessage,
    findMessage,
    updateMessage,
    clearMessages,
    messages,
  }
}

export type ChatMessagesManager = ReturnType<typeof useMessages>;

export const LocalMessageIdPool = {
  id: 0,
  getNextId: () => {
    LocalMessageIdPool.id--;
    return LocalMessageIdPool.id;
  },
}


export function mergeSystemMessages(messages: OpenAI.Chat.ChatCompletionSystemMessageParam[]) {
  if (!messages || messages.length === 0) return [];

  // 将所有内容合并成一条消息，使用换行分隔
  const combinedContent = messages
    .map(msg => {
      if (typeof msg.content === 'string')
        return msg.content?.trim()
       return msg.content.map(part => part.text).join('\n\n');
    })
    .filter(Boolean)
    .join('\n\n');
  
  if (!combinedContent) 
    return [];

  return [
    {
      role: 'system',
      content: combinedContent,
    } as OpenAI.Chat.ChatCompletionSystemMessageParam
  ];
}