/**
 * Tools API Routes
 *
 * 工具管理相关的 REST API
 */

import { Hono } from 'hono';
import type { Tool } from '../types.js';

export const toolsRouter = new Hono();

// 工具注册表 (后续会从 core 模块获取)
const toolRegistry: Map<string, Tool> = new Map();

/**
 * 注册工具 (内部使用)
 */
export function registerTool(tool: Tool): void {
  toolRegistry.set(tool.name, tool);
}

/**
 * 获取所有已注册的工具
 */
export function getRegisteredTools(): Tool[] {
  return Array.from(toolRegistry.values());
}

/**
 * GET /tools - 列出所有可用工具
 */
toolsRouter.get('/', (c) => {
  const tools = getRegisteredTools();

  return c.json({
    success: true,
    data: tools,
  });
});

/**
 * GET /tools/:name - 获取单个工具详情
 */
toolsRouter.get('/:name', (c) => {
  const name = c.req.param('name');
  const tool = toolRegistry.get(name);

  if (!tool) {
    return c.json(
      {
        success: false,
        error: 'Tool not found',
      },
      404
    );
  }

  return c.json({
    success: true,
    data: tool,
  });
});

/**
 * POST /tools/:name/execute - 执行工具
 *
 * 注意: 工具执行是同步的，对于长时间运行的工具，
 * 建议通过 WebSocket 执行以获取实时反馈。
 */
toolsRouter.post('/:name/execute', async (c) => {
  const name = c.req.param('name');
  const tool = toolRegistry.get(name);

  if (!tool) {
    return c.json(
      {
        success: false,
        error: 'Tool not found',
      },
      404
    );
  }

  try {
    const body = await c.req.json();
    const params = body.params || {};

    // TODO: 实际调用 core 模块的工具执行逻辑
    // const result = await executeTool(name, params);

    return c.json({
      success: true,
      data: {
        tool: name,
        params,
        result: null, // 占位，后续实现
        message: 'Tool execution not yet implemented',
      },
    });
  } catch (error) {
    return c.json(
      {
        success: false,
        error: error instanceof Error ? error.message : 'Execution failed',
      },
      500
    );
  }
});
