/**
 * Claude API Connector
 */
import Anthropic from '@anthropic-ai/sdk';
import type { LLMConnector, LLMResult, LLMConfig } from '../types.js';

export class ClaudeConnector implements LLMConnector {
  private client: Anthropic;

  constructor(apiKey?: string) {
    this.client = new Anthropic({
      apiKey: apiKey || process.env.ANTHROPIC_API_KEY,
    });

    if (!this.client.apiKey) {
      throw new Error(
        '缺少 ANTHROPIC_API_KEY\n' +
        '请设置环境变量: export ANTHROPIC_API_KEY=your-key\n' +
        '或在 workflow YAML 中配置'
      );
    }
  }

  async chat(systemPrompt: string, userMessage: string, config: LLMConfig): Promise<LLMResult> {
    const response = await this.client.messages.create({
      model: config.model!,
      max_tokens: config.max_tokens || 4096,
      system: systemPrompt,
      messages: [
        { role: 'user', content: userMessage },
      ],
    });

    const content = response.content
      .filter(block => block.type === 'text')
      .map(block => block.type === 'text' ? block.text : '')
      .join('\n');

    return {
      content,
      usage: {
        input_tokens: response.usage.input_tokens,
        output_tokens: response.usage.output_tokens,
      },
    };
  }
}
