/**
 * Web 插件测试示例
 * 测试路由注册和请求响应
 */

const { WebPlugin } = require('../plugins/web-plugin');

async function test() {
  console.log('=== Web 插件测试 ===\n');

  // 1. 创建插件
  const plugin = new WebPlugin();
  const mockFramework = {
    registerTool: (tool) => console.log(`[工具注册] ${tool.name}`),
    _agents: [],
    pluginManager: { get: () => null },
  };
  plugin.install(mockFramework);

  // 2. 启动服务
  console.log('\n[1] 启动 Web 服务...');
  const startResult = await plugin._startServer(3099);
  console.log('启动结果:', startResult.success ? '成功' : '失败');
  console.log('服务地址: http://localhost:3099\n');

  // 3. 注册测试路由
  console.log('[2] 注册测试路由...');

  // 返回固定字符串
  await plugin._registerRoute('GET', '/test', 'return "1232432"', '返回固定字符串');
  console.log('注册: GET /test -> return "1232432"');

  // 返回 JSON
  await plugin._registerRoute('GET', '/json', 'return { hello: "world", code: 200 }', '返回 JSON');
  console.log('注册: GET /json -> return { hello: "world", code: 200 }');

  // 带参数
  await plugin._registerRoute(
    'GET',
    '/user/:id',
    'return { userId: context.params.id }',
    '路径参数'
  );
  console.log('注册: GET /user/:id -> return { userId: context.params.id }');

  // POST 路由
  await plugin._registerRoute('POST', '/echo', 'return { received: context.body }', '回显 body');
  console.log('注册: POST /echo -> return { received: context.body }');

  // 4. 等待服务就绪
  await new Promise((r) => setTimeout(r, 500));

  // 5. 测试各路由
  console.log('\n[3] 测试路由响应...\n');

  // GET /test
  console.log('GET /test:');
  const r1 = await plugin._sendRequest('GET', '/test');
  console.log('  状态:', r1.status);
  console.log('  响应:', JSON.stringify(r1.body));
  console.log();

  // GET /json
  console.log('GET /json:');
  const r2 = await plugin._sendRequest('GET', '/json');
  console.log('  状态:', r2.status);
  console.log('  响应:', JSON.stringify(r2.body));
  console.log();

  // GET /user/123
  console.log('GET /user/123:');
  const r3 = await plugin._sendRequest('GET', '/user/123');
  console.log('  状态:', r3.status);
  console.log('  响应:', JSON.stringify(r3.body));
  console.log();

  // POST /echo
  console.log('POST /echo (body: { name: "test" }):');
  const r4 = await plugin._sendRequest('POST', '/echo', { name: 'test' });
  console.log('  状态:', r4.status);
  console.log('  响应:', JSON.stringify(r4.body));
  console.log();

  // 6. 列出所有路由
  console.log('[4] 已注册的路由:');
  const routes = plugin._listRoutes();
  routes.routes.forEach((r) => {
    console.log(`  ${r.method} ${r.path} - ${r.description}`);
  });
  routes.webhooks.forEach((w) => {
    console.log(`  WEBHOOK ${w.path}`);
  });
  routes.statics.forEach((s) => {
    console.log(`  STATIC ${s.path} -> ${s.folder}`);
  });

  // 7. 停止服务
  console.log('\n[5] 停止服务...');
  await plugin._stopServer();
  console.log('测试完成!');
}

test().catch(console.error);
