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

// Mock fs/promises
vi.mock('fs/promises', () => ({
  readdir: vi.fn(),
}));

// 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(() => '列出目录内容'),
}));

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

describe('listDirTool - 列出目录工具', () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

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

    it('有正确的元数据', () => {
      expect(listDirTool.metadata.category).toBe('filesystem');
      expect(listDirTool.metadata.keywords).toContain('list');
      expect(listDirTool.metadata.keywords).toContain('directory');
      expect(listDirTool.metadata.keywords).toContain('ls');
    });

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

  describe('execute - 执行', () => {
    it('成功列出目录内容', async () => {
      vi.mocked(fs.readdir).mockResolvedValue([
        { name: 'file1.txt', isDirectory: () => false },
        { name: 'folder', isDirectory: () => true },
        { name: 'file2.js', isDirectory: () => false },
      ] as any);

      const result = await listDirTool.execute({ path: './' });

      expect(result.success).toBe(true);
      expect(result.output).toContain('file1.txt');
      expect(result.output).toContain('folder');
      expect(result.output).toContain('file2.js');
    });

    it('使用正确的图标区分文件和目录', async () => {
      vi.mocked(fs.readdir).mockResolvedValue([
        { name: 'file.txt', isDirectory: () => false },
        { name: 'folder', isDirectory: () => true },
      ] as any);

      const result = await listDirTool.execute({ path: './' });

      expect(result.output).toMatch(/📄.*file\.txt/);
      expect(result.output).toMatch(/📁.*folder/);
    });

    it('空目录显示提示', async () => {
      vi.mocked(fs.readdir).mockResolvedValue([]);

      const result = await listDirTool.execute({ path: './' });

      expect(result.success).toBe(true);
      expect(result.output).toBe('(空目录)');
    });

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

      const result = await listDirTool.execute({ path: '/etc' });

      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 listDirTool.execute({ path: '/home/user' });

      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.readdir).mockRejectedValue(new Error('ENOENT: no such directory'));

      const result = await listDirTool.execute({ path: './nonexistent' });

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

    it('使用 withFileTypes 选项调用 readdir', async () => {
      vi.mocked(fs.readdir).mockResolvedValue([]);

      await listDirTool.execute({ path: './' });

      expect(fs.readdir).toHaveBeenCalledWith(
        expect.any(String),
        { withFileTypes: true }
      );
    });
  });
});
