import { describe, it, expect, beforeEach, vi } from 'vitest';
import { writeFileTool } from '../../../../src/tools/filesystem/write_file.js';

// Mock fs/promises
vi.mock('fs/promises', () => ({
  mkdir: vi.fn().mockResolvedValue(undefined),
  writeFile: vi.fn().mockResolvedValue(undefined),
}));

// Mock permission manager
vi.mock('../../../../src/permission/index.js', () => ({
  getPermissionManager: vi.fn(() => ({
    checkFilePermission: vi.fn().mockResolvedValue({
      allowed: true,
      action: 'allow',
    }),
  })),
}));

// Mock loadDescription
vi.mock('../../../../src/tools/load_description.js', () => ({
  loadDescription: vi.fn(() => '写入文件内容'),
}));

// Mock LSP
vi.mock('../../../../src/lsp/index.js', () => ({
  touchFile: vi.fn().mockResolvedValue(false),
  getFormattedFileDiagnostics: vi.fn().mockResolvedValue(null),
  isLanguageSupported: vi.fn().mockReturnValue(false),
}));

import * as fs from 'fs/promises';
import { getPermissionManager } from '../../../../src/permission/index.js';

describe('writeFileTool - 写入文件工具', () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  describe('工具定义', () => {
    it('有正确的名称', () => {
      expect(writeFileTool.name).toBe('write_file');
    });

    it('有正确的元数据', () => {
      expect(writeFileTool.metadata.category).toBe('filesystem');
      expect(writeFileTool.metadata.keywords).toContain('write');
      expect(writeFileTool.metadata.keywords).toContain('save');
    });

    it('定义了必需的参数', () => {
      expect(writeFileTool.parameters.path).toBeDefined();
      expect(writeFileTool.parameters.path.required).toBe(true);
      expect(writeFileTool.parameters.content).toBeDefined();
      expect(writeFileTool.parameters.content.required).toBe(true);
    });
  });

  describe('execute - 执行', () => {
    it('成功写入文件', async () => {
      const result = await writeFileTool.execute({
        path: './test.txt',
        content: 'Hello, World!',
      });

      expect(result.success).toBe(true);
      expect(result.output).toContain('文件已写入');
    });

    it('创建必要的目录', async () => {
      await writeFileTool.execute({
        path: './deep/nested/file.txt',
        content: 'content',
      });

      expect(fs.mkdir).toHaveBeenCalledWith(
        expect.any(String),
        { recursive: true }
      );
    });

    it('权限被拒绝时返回错误', async () => {
      vi.mocked(getPermissionManager).mockReturnValue({
        checkFilePermission: vi.fn().mockResolvedValue({
          allowed: false,
          action: 'deny',
          reason: '不允许写入此文件',
        }),
      } as any);

      const result = await writeFileTool.execute({
        path: '/etc/passwd',
        content: 'malicious',
      });

      expect(result.success).toBe(false);
      expect(result.error).toContain('权限被拒绝');
    });

    it('需要确认时返回提示', async () => {
      vi.mocked(getPermissionManager).mockReturnValue({
        checkFilePermission: vi.fn().mockResolvedValue({
          allowed: false,
          action: 'ask',
          needsConfirmation: true,
        }),
      } as any);

      const result = await writeFileTool.execute({
        path: './new-file.txt',
        content: 'content',
      });

      expect(result.success).toBe(false);
      expect(result.error).toContain('需要用户确认');
    });

    it('写入失败时返回错误', async () => {
      vi.mocked(getPermissionManager).mockReturnValue({
        checkFilePermission: vi.fn().mockResolvedValue({
          allowed: true,
          action: 'allow',
        }),
      } as any);
      vi.mocked(fs.writeFile).mockRejectedValue(new Error('Write failed'));

      const result = await writeFileTool.execute({
        path: './test.txt',
        content: 'content',
      });

      expect(result.success).toBe(false);
      expect(result.error).toContain('Write failed');
    });

    it('传递 newContent 给权限检查', async () => {
      const mockCheck = vi.fn().mockResolvedValue({
        allowed: true,
        action: 'allow',
      });
      vi.mocked(getPermissionManager).mockReturnValue({
        checkFilePermission: mockCheck,
      } as any);

      await writeFileTool.execute({
        path: './test.txt',
        content: 'new content',
      });

      expect(mockCheck).toHaveBeenCalledWith(
        expect.objectContaining({
          operation: 'write',
          newContent: 'new content',
        })
      );
    });
  });
});
