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 listDirTool: ToolWithMetadata = {
  name: 'list_directory',
  description: loadDescription('list_directory'),
  metadata: {
    name: 'list_directory',
    category: 'filesystem',
    description: '列出目录内容',
    keywords: ['list', 'directory', 'ls', 'dir', 'folder', '列出', '目录', '文件夹', '查看'],
    deferLoading: true,
  },
  parameters: {
    path: {
      type: 'string',
      description: '要列出的目录路径',
      required: true,
    },
  },
  execute: async (params: Record<string, unknown>): Promise<ToolResult> => {
    const dirPath = params.path as string;
    const cwd = process.cwd();
    const absolutePath = path.isAbsolute(dirPath)
      ? dirPath
      : path.join(cwd, dirPath);

    // 权限检查
    const permissionManager = getPermissionManager();
    const permResult = await permissionManager.checkFilePermission({
      operation: 'list',
      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 entries = await fs.readdir(absolutePath, { withFileTypes: true });
      const result = entries
        .map((entry) => {
          const prefix = entry.isDirectory() ? '📁' : '📄';
          return `${prefix} ${entry.name}`;
        })
        .join('\n');

      return {
        success: true,
        output: result || '(空目录)',
      };
    } catch (error) {
      return {
        success: false,
        output: '',
        error: error instanceof Error ? error.message : String(error),
      };
    }
  },
};
