import type OpenAI from "openai";
import { ref, computed, type Ref } from "vue";
import type { ChatMessage } from "../model/Message";

export type ChatToolContext = {
  /**
   * 当前会话消息列表（同 ChatHome 的 messages）
   */
  messages: Ref<ChatMessage[]>;
  /**
   * 触发一次滚动到底部（可选）
   */
  scrollToBottom?: () => void | Promise<void>;
};

export type ChatToolHandler = (args: any, ctx: ChatToolContext) => Promise<string | object> | string | object;

export type ChatToolDefinition = {
  /**
   * OpenAI tools[].function.name
   */
  name: string;
  /**
   * OpenAI tools[].function.description
   */
  description?: string;
  /**
   * OpenAI tools[].function.parameters (JSON Schema)
   */
  parameters?: Record<string, any>;
  /**
   * 当模型触发 tool_calls 时执行
   */
  handler: ChatToolHandler;
};

export type ChatToolsManager = {
  registerTool: (tool: ChatToolDefinition) => void;
  unregisterTool: (name: string) => void;
  clearTools: () => void;
  toolRegistry: Ref<Map<string, ChatToolDefinition>>;
  openAiTools: Ref<OpenAI.Chat.Completions.ChatCompletionTool[]>;
};

export function useChatTools(): ChatToolsManager {
  const toolRegistry = ref(new Map<string, ChatToolDefinition>());
  const openAiTools = computed<OpenAI.Chat.Completions.ChatCompletionTool[]>(() => {
    const arr: OpenAI.Chat.Completions.ChatCompletionTool[] = [];
    for (const [, def] of toolRegistry.value) {
      arr.push({
        type: "function",
        function: {
          name: def.name,
          description: def.description,
          parameters: def.parameters ?? { type: "object", properties: {} },
        },
      });
    }
    return arr;
  });

  function registerTool(tool: ChatToolDefinition) {
    toolRegistry.value.set(tool.name, tool);
  }
  function unregisterTool(name: string) {
    toolRegistry.value.delete(name);
  }
  function clearTools() {
    toolRegistry.value.clear();
  }

  return {
    registerTool,
    unregisterTool,
    clearTools,
    toolRegistry,
    openAiTools,
  };
}
