import { describe, it, expect, beforeEach, vi } from 'vitest';

// 定义一个可控的 mock
let mockExecAsyncResult: { stdout: string; stderr: string } | Error = {
  stdout: 'On branch main\nnothing to commit',
  stderr: '',
};

// Mock child_process
vi.mock('child_process', () => ({
  exec: vi.fn(),
}));

// Mock util - 返回一个函数，该函数使用外部变量
vi.mock('util', () => ({
  promisify: vi.fn(() => vi.fn(async () => {
    if (mockExecAsyncResult instanceof Error) {
      throw mockExecAsyncResult;
    }
    return mockExecAsyncResult;
  })),
}));

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

// Mock loadDescription
vi.mock('../../../../src/tools/load_description.js', () => ({
  loadDescription: vi.fn(() => '查看 Git 仓库状态'),
}));

import { gitStatusTool } from '../../../../src/tools/git/git_status.js';
import { getPermissionManager } from '../../../../src/permission/index.js';

describe('gitStatusTool - Git 状态工具', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    mockExecAsyncResult = {
      stdout: 'On branch main\nnothing to commit',
      stderr: '',
    };
  });

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

    it('有正确的元数据', () => {
      expect(gitStatusTool.metadata.category).toBe('git');
      expect(gitStatusTool.metadata.keywords).toContain('git');
      expect(gitStatusTool.metadata.keywords).toContain('status');
    });

    it('定义了可选参数', () => {
      expect(gitStatusTool.parameters.short).toBeDefined();
      expect(gitStatusTool.parameters.short.required).toBe(false);
      expect(gitStatusTool.parameters.branch).toBeDefined();
      expect(gitStatusTool.parameters.branch.required).toBe(false);
    });
  });

  describe('execute - 执行', () => {
    it('成功获取状态', async () => {
      const result = await gitStatusTool.execute({});

      expect(result.success).toBe(true);
      expect(result.output).toContain('On branch main');
    });

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

      const result = await gitStatusTool.execute({});

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

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

      const result = await gitStatusTool.execute({});

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

    it('非 git 仓库返回错误', async () => {
      vi.mocked(getPermissionManager).mockReturnValue({
        checkGitPermission: vi.fn().mockResolvedValue({
          allowed: true,
          action: 'allow',
        }),
      } as any);
      mockExecAsyncResult = Object.assign(
        new Error('Command failed'),
        { stderr: 'fatal: not a git repository', stdout: '' }
      );

      const result = await gitStatusTool.execute({});

      expect(result.success).toBe(false);
      expect(result.error).toContain('not a git repository');
    });

    it('包含 stderr 输出', async () => {
      mockExecAsyncResult = {
        stdout: 'main output',
        stderr: 'warning message',
      };

      const result = await gitStatusTool.execute({});

      expect(result.success).toBe(true);
      expect(result.output).toContain('main output');
      expect(result.output).toContain('warning message');
    });
  });
});
