import { AnthropicProvider } from './anthropic.provider';

const mockCreate = jest.fn();

jest.mock('@anthropic-ai/sdk', () => ({
  __esModule: true,
  default: jest.fn().mockImplementation(() => ({
    messages: {
      create: mockCreate,
    },
  })),
}));

describe('AnthropicProvider', () => {
  beforeEach(() => {
    mockCreate.mockReset();
  });

  it('reports stop reason and text preview when no tool_use block is returned', async () => {
    mockCreate.mockResolvedValue({
      stop_reason: 'end_turn',
      model: 'claude-test',
      content: [
        {
          type: 'text',
          text: '我理解你的意思，但这里没有可识别的 QY 编号，所以我先用自然语言解释。',
        },
      ],
      usage: {
        input_tokens: 12,
        output_tokens: 34,
      },
    });

    const provider = new AnthropicProvider('test-key', 'https://example.test');

    await expect(
      provider.callTool({
        systemPrompt: '只通过工具返回',
        userPrompt: '拆解这个原型',
        tool: {
          name: 'submit_decompose',
          description: '提交拆解结果',
          inputSchema: {
            type: 'object',
            properties: { ok: { type: 'boolean' } },
            required: ['ok'],
          },
        },
        forceTool: true,
        maxTokens: 1000,
        model: 'claude-test',
      }),
    ).rejects.toThrow(
      /Anthropic 未通过 tool_use 返回结果.*stop_reason=end_turn.*content=text\("我理解你的意思/,
    );
  });

  it('disables parallel tool use when a specific tool is forced', async () => {
    mockCreate.mockResolvedValue({
      stop_reason: 'tool_use',
      model: 'claude-test',
      content: [
        {
          type: 'tool_use',
          id: 'toolu_test',
          name: 'submit_decompose',
          input: { ok: true },
        },
      ],
      usage: {
        input_tokens: 12,
        output_tokens: 34,
      },
    });

    const provider = new AnthropicProvider('test-key', 'https://example.test');

    await provider.callTool({
      systemPrompt: '只通过工具返回',
      userPrompt: '拆解这个原型',
      tool: {
        name: 'submit_decompose',
        description: '提交拆解结果',
        inputSchema: {
          type: 'object',
          properties: { ok: { type: 'boolean' } },
          required: ['ok'],
        },
      },
      forceTool: true,
      maxTokens: 1000,
      model: 'claude-test',
    });

    expect(mockCreate).toHaveBeenCalledWith(
      expect.objectContaining({
        tool_choice: {
          type: 'tool',
          name: 'submit_decompose',
          disable_parallel_tool_use: true,
        },
      }),
    );
  });
});
