import "dotenv/config";
import { MemorySaver } from "@langchain/langgraph";
import { createAgent } from "langchain";
import { HumanMessage } from "@langchain/core/messages";
import { MultiServerMCPClient } from "@langchain/mcp-adapters";
// 导入readline模块用于从终端读取输入
import readline from "readline";

// 从tools目录导入工具
import { agentTools } from "./tools/index.js";

// 从模型配置文件导入模型实例
import { agentModel } from "./config/modelConfig.js";

// 从MCP配置文件导入MCP服务配置
import { mcpServersConfig } from "./config/mcpConfig.js";

const agentCheckpoint = new MemorySaver();

// 导出agent创建函数,支持异步获取MCP工具
export const createAgentWithMCP = async () => {
  try {
    // 检查是否配置了MCP服务器
    const hasMCPServers = Object.keys(mcpServersConfig).length > 0;
    let allTools = [...agentTools];

    if (hasMCPServers) {
      // 创建MCP客户端实例
      const mcpClient = new MultiServerMCPClient(mcpServersConfig);
      const mcpTools = await mcpClient.getTools();
      console.log(
        "Successfully loaded MCP tools:",
        mcpTools.map((tool) => tool.name),
      );
      // 合并本地工具和外部MCP工具
      allTools = [...agentTools, ...mcpTools];
    } else {
      console.log("No MCP servers configured, using only local tools");
    }

    return createAgent({
      model: agentModel,
      tools: allTools,
      checkpointSaver: agentCheckpoint,
    });
  } catch (error) {
    // 如果MCP初始化失败,使用本地工具创建agent
    return createAgent({
      model: agentModel,
      tools: agentTools,
      checkpointSaver: agentCheckpoint,
    });
  }
};

// 导出agent实例(用于向后兼容)
export let agent;

// 执行交互式测试,从终端接收输入
async function runInteractiveTest() {
  // 创建readline接口
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
  });
  try {
    const initializedAgent = await createAgentWithMCP();
    console.log('Agent已初始化,开始交互式调试。输入"exit"退出。');

    // 递归函数处理用户输入
    async function handleUserInput() {
      rl.question("You: ", async (input) => {
        if (input.toLowerCase() === "exit") {
          console.log("再见!");
          rl.close();
          return;
        }

        try {
          const result = await initializedAgent.invoke(
            { messages: [new HumanMessage(input)] },
            { configurable: { thread_id: "test" } },
          );
          console.log(
            "Agent:",
            result.messages
          );
        } catch (error) {
          console.log("错误详情:", error);
        }

        // 继续处理下一个输入
        handleUserInput();
      });
    }

    // 开始处理用户输入
    handleUserInput();
  } catch (error) {
    console.log("错误详情:", error);
    rl.close();
  }
}

// 仅当直接运行此文件时才执行测试
const importUrl = new URL(import.meta.url);
const processPath = new URL(`file://${process.argv[1]}`);
const isDirectRun = importUrl.href === processPath.href;

if (isDirectRun) {
  runInteractiveTest();
} else {
  createAgentWithMCP()
    .then((instance) => {
      agent = instance;
    })
    .catch((error) => {
      console.error("Failed to initialize agent with MCP tools:", error);
    });
}

/*
async function runSimpleTest() {
  const initializedAgent = await createAgentWithMCP();
  const result = await initializedAgent.invoke(
    { messages: [new HumanMessage("你好,请介绍一下你自己")] },
    { configurable: { thread_id: "test" } },
  );
  console.log(result.messages[result.messages.length - 1].content);
}
*/