import Anthropic from '@anthropic-ai/sdk';

let anthropic: Anthropic | null = null;

const getAnthropic = () => {
  if (!anthropic) {
    const apiKey = process.env.ANTHROPIC_API_KEY || process.env.CLAUDE_API_KEY;
    if (!apiKey) {
      throw new Error('ANTHROPIC_API_KEY environment variable is not set');
    }
    anthropic = new Anthropic({ apiKey });
  }
  return anthropic;
};

export const getClaudeClient = () => {
  return {
    generate: async (prompt: string) => {
      const client = getAnthropic();
      
      // Create a timeout promise
      const timeoutPromise = new Promise((_, reject) => {
        setTimeout(() => reject(new Error('Claude API request timed out after 90 seconds')), 90000);
      });
      
      try {
        const response = await Promise.race([
          client.messages.create({
            model: 'claude-3-opus-20240229',
            max_tokens: 2048,
            messages: [{ role: 'user', content: prompt }],
          }),
          timeoutPromise
        ]) as Anthropic.Messages.Message;
        
        const content = response.content[0];
        if (content.type === 'text') {
          return content.text;
        }
        throw new Error('Unexpected content type from Claude API');
      } catch (error) {
        console.error('Claude API error:', error);
        throw error;
      }
    },
  };
};
