/**
 * 测试并发 chat 调用
 */

const { Framework } = require('../src');
const AIPlugin = require('../plugins/ai-plugin');
const SessionPlugin = require('../plugins/session-plugin');
require('dotenv').config();

async function main() {
  console.log('=== 测试并发 chat 调用 ===\n');

  const framework = new Framework({ debug: false });

  await framework.loadPlugin(
    new AIPlugin({
      provider: 'minimax',
      model: 'MiniMax-M2.7',
      apiKey: process.env.MINIMAX_API_KEY || 'your-api-key',
    })
  );
  await framework.loadPlugin(new SessionPlugin());

  const systemPrompt = `你是一个微信助手。`;

  // 创建一个 agent（模拟单个用户）
  const agent = framework.createAgent({
    name: 'WeixinAgent',
    systemPrompt: systemPrompt,
  });

  const sessionId = 'weixin_test_user';
  const sessionPlugin = framework.pluginManager.get('session');
  sessionPlugin.getOrCreateSession(sessionId, { metadata: { platform: 'weixin' } });

  // 模拟 3 个并发 chat 调用
  console.log('\n--- 并发发送 3 条消息 ---');

  const results = await Promise.all([
    agent.chat('你好', { sessionId }),
    agent.chat('今天天气怎么样？', { sessionId }),
    agent.chat('帮我查一下天气', { sessionId }),
  ]);

  console.log('\n--- 结果 ---');
  for (let i = 0; i < results.length; i++) {
    const r = results[i];
    console.log(`[${i}] message length: ${r.message?.length || 'EMPTY'}`);
    console.log(`[${i}] message: ${r.message?.substring(0, 50) || 'EMPTY'}...`);
  }

  // 检查 _messages 状态
  const chatHandler = agent._chatHandler;
  console.log(`\n[DEBUG] _messages count: ${chatHandler?._messages.length}`);

  await framework.destroy();
  console.log('\n[Done]');
}

main().catch(console.error);
