/**
 * 编辑文件工具
 *
 * 使用统一的编辑模式系统
 */

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';
import {
  createSingleSearchReplaceEdit,
  applyEdit,
  validateEdit,
} from '../../editors/index.js';

export const editFileTool: ToolWithMetadata = {
  name: 'edit_file',
  description: loadDescription('edit_file'),
  metadata: {
    name: 'edit_file',
    category: 'filesystem',
    description: '编辑文件内容（查找替换）',
    keywords: ['edit', 'file', 'replace', 'modify', 'change', 'update', '编辑', '文件', '替换', '修改', '更新'],
    deferLoading: false, // 核心工具，始终可用
  },
  parameters: {
    path: {
      type: 'string',
      description: '要编辑的文件路径',
      required: true,
    },
    old_string: {
      type: 'string',
      description: '要被替换的原始字符串（必须精确匹配）',
      required: true,
    },
    new_string: {
      type: 'string',
      description: '替换后的新字符串',
      required: true,
    },
  },
  execute: async (params: Record<string, unknown>): Promise<ToolResult> => {
    const filePath = params.path as string;
    const oldString = params.old_string as string;
    const newString = params.new_string as string;
    const cwd = process.cwd();
    const absolutePath = path.isAbsolute(filePath)
      ? filePath
      : path.join(cwd, filePath);

    // 创建编辑对象
    const edit = createSingleSearchReplaceEdit(absolutePath, oldString, newString);

    // 先验证
    const validation = await validateEdit(edit);
    if (!validation.valid) {
      // 格式化错误信息
      const errorMessages = validation.errors
        .map((e) => {
          if (e.type === 'not_found') {
            return `未找到要替换的字符串。请确保 old_string 与文件中的内容完全匹配（包括空格和换行）。`;
          }
          if (e.type === 'ambiguous') {
            return `找到 ${e.occurrences} 处匹配。old_string 必须唯一，请提供更多上下文使其唯一。`;
          }
          return e.message;
        })
        .join('\n');

      return {
        success: false,
        output: '',
        error: errorMessages,
      };
    }

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

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

    // 应用编辑
    const result = await applyEdit(edit, {
      validate: false, // 已经验证过了
      runDiagnostics: true,
    });

    if (!result.success) {
      return {
        success: false,
        output: '',
        error: result.error || '编辑失败',
      };
    }

    // 构建输出
    let output = `文件已编辑: ${absolutePath}`;

    if (result.diagnostics) {
      output += `\n\n⚠️ 代码检查发现问题，请修复:${result.diagnostics}`;
    }

    return {
      success: true,
      output,
    };
  },
};
