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 searchFilesTool: ToolWithMetadata = {
  name: 'search_files',
  description: loadDescription('search_files'),
  metadata: {
    name: 'search_files',
    category: 'filesystem',
    description: '按文件名搜索文件',
    keywords: ['search', 'file', 'find', 'glob', 'pattern', '搜索', '文件', '查找', '匹配'],
    deferLoading: true,
  },
  parameters: {
    directory: {
      type: 'string',
      description: '搜索的起始目录',
      required: true,
    },
    pattern: {
      type: 'string',
      description: '文件名匹配模式（支持 glob 模式，如 *.ts）',
      required: true,
    },
  },
  execute: async (params: Record<string, unknown>): Promise<ToolResult> => {
    const directory = params.directory as string;
    const pattern = params.pattern as string;
    const cwd = process.cwd();
    const absolutePath = path.isAbsolute(directory)
      ? directory
      : path.join(cwd, directory);

    // 权限检查
    const permissionManager = getPermissionManager();
    const permResult = await permissionManager.checkFilePermission({
      operation: 'search',
      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 || '不允许搜索此目录'}`,
      };
    }

    const matches: string[] = [];
    const regex = new RegExp(
      pattern.replace(/\*/g, '.*').replace(/\?/g, '.'),
      'i'
    );

    async function searchRecursive(dir: string, depth = 0): Promise<void> {
      if (depth > 10) return;

      try {
        const entries = await fs.readdir(dir, { withFileTypes: true });
        for (const entry of entries) {
          const fullPath = path.join(dir, entry.name);

          if (entry.name.startsWith('.') || entry.name === 'node_modules') {
            continue;
          }

          if (entry.isDirectory()) {
            await searchRecursive(fullPath, depth + 1);
          } else if (regex.test(entry.name)) {
            matches.push(fullPath);
          }
        }
      } catch {
        // 忽略权限错误
      }
    }

    try {
      await searchRecursive(absolutePath);
      return {
        success: true,
        output:
          matches.length > 0
            ? matches.join('\n')
            : '没有找到匹配的文件',
      };
    } catch (error) {
      return {
        success: false,
        output: '',
        error: error instanceof Error ? error.message : String(error),
      };
    }
  },
};
