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

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

export const writeFileTool: ToolWithMetadata = {
  name: 'write_file',
  description: loadDescription('write_file'),
  metadata: {
    name: 'write_file',
    category: 'filesystem',
    description: '写入文件内容',
    keywords: ['write', 'file', 'save', 'create', '写入', '文件', '保存', '创建', '新建'],
    deferLoading: false, // 核心工具，始终可用
  },
  parameters: {
    path: {
      type: 'string',
      description: '要写入的文件路径',
      required: true,
    },
    content: {
      type: 'string',
      description: '要写入的内容',
      required: true,
    },
  },
  execute: async (params: Record<string, unknown>): Promise<ToolResult> => {
    const filePath = params.path as string;
    const content = params.content 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: 'write',
      path: absolutePath,
      workdir: cwd,
      newContent: content,
    });

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

    // 创建编辑对象
    const edit = createWholeFileEdit(absolutePath, content);

    // 应用编辑
    const result = await applyEdit(edit, {
      validate: true,
      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,
    };
  },
};
