/**
 * 测试长对话压缩场景
 */

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

async function main() {
  console.log('=== 测试长对话压缩场景 ===\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 = `你是一个有帮助的助手。`;

  const agent = framework.createAgent({
    name: 'TestAgent',
    systemPrompt: systemPrompt,
  });

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

  // 发送多条长消息来触发压缩
  const longContent = `请详细描述以下内容：人工智能的发展历史、现状和未来趋势。包括机器学习、深度学习、自然语言处理等核心技术的发展历程，以及在各个行业中的应用场景。同时分析当前面临的挑战，如数据隐私、算法偏见、能源消耗等问题。`;

  console.log('--- 发送 15 条长消息 ---');
  for (let i = 1; i <= 15; i++) {
    try {
      const result = await agent.chat(`${longContent}\n\n[消息 ${i}]`, { sessionId });
      const msgLen = result.message?.length || 0;
      console.log(`[${i}] message length: ${msgLen}, success: ${result.success}`);

      if (!result.message) {
        console.log(`[ERROR] message is empty!`);
        console.log(`[DEBUG] result:`, JSON.stringify(result, null, 2));
        break;
      }
    } catch (err) {
      console.error(`[${i}] Error:`, err.message);
    }
  }

  // 检查压缩统计
  const chatHandler = agent._chatHandler;
  console.log(`\n[DEBUG] compression count: ${chatHandler?._compressionCount}`);
  console.log(`[DEBUG] _messages count: ${chatHandler?._messages.length}`);

  // 压缩后再发一条
  console.log('\n--- 压缩后发送测试 ---');
  try {
    const result = await agent.chat('你好，压缩后你还认识我吗？', { sessionId });
    console.log(`message length: ${result.message?.length || 0}`);
    console.log(`message: ${result.message?.substring(0, 100)}`);
    if (!result.message) {
      console.log(`[ERROR] message is empty after compression!`);
    }
  } catch (err) {
    console.error(`Error:`, err.message);
  }

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

main().catch(console.error);
