import * as fs from 'fs/promises';
import * as path from 'path';
import type { ToolResult } from '../../types/index.js';
import type { ToolWithMetadata } from '../types.js';
import { loadDescription } from '../load_description.js';
import { getPermissionManager } from '../../permission/index.js';

export const readFileTool: ToolWithMetadata = {
  name: 'read_file',
  description: loadDescription('read_file'),
  metadata: {
    name: 'read_file',
    category: 'filesystem',
    description: '读取文件内容',
    keywords: ['read', 'file', 'content', 'cat', 'view', 'open', '读取', '文件', '内容', '查看', '打开'],
    deferLoading: false, // 核心工具，始终可用
  },
  parameters: {
    path: {
      type: 'string',
      description: '要读取的文件路径（相对或绝对路径）',
      required: true,
    },
  },
  execute: async (params: Record<string, unknown>): Promise<ToolResult> => {
    const filePath = params.path as string;
    const cwd = process.cwd();
    const absolutePath = path.isAbsolute(filePath)
      ? filePath
      : path.join(cwd, filePath);

    // 权限检查
    const permissionManager = getPermissionManager();
    const permResult = await permissionManager.checkFilePermission({
      operation: 'read',
      path: absolutePath,
      workdir: cwd,
    });

    if (!permResult.allowed) {
      if (permResult.needsConfirmation) {
        return {
          success: false,
          output: '',
          error: `需要用户确认: 读取 ${absolutePath}\n原因: ${permResult.reason || '需要权限确认'}`,
        };
      }
      return {
        success: false,
        output: '',
        error: `权限被拒绝: ${permResult.reason || '不允许读取此文件'}`,
      };
    }

    try {
      const content = await fs.readFile(absolutePath, 'utf-8');
      return {
        success: true,
        output: content,
      };
    } catch (error) {
      return {
        success: false,
        output: '',
        error: error instanceof Error ? error.message : String(error),
      };
    }
  },
};
