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

// Initialize Anthropic client
const anthropic = new Anthropic({
  apiKey: process.env.REACT_APP_ANTHROPIC_API_KEY  || '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',
  dangerouslyAllowBrowser: true // Only for development
});

export const analyzeFeatureWithAI = async (featureName, description, requirements) => {
  try {
    console.log('🧠 AI analyzing feature:', featureName);
    
    console.log('🔑 API Key available:', !!process.env.REACT_APP_ANTHROPIC_API_KEY); // ADD THIS
    
    const requirementsText = requirements
      .filter(req => req.trim())
      .map(req => `- ${req}`)
      .join('\n');

    const prompt = `
    Analyze this feature and provide complexity assessment and business logic rules:

    Feature Name: ${featureName}
    Description: ${description}
    
    Requirements:
    ${requirementsText}

    Based on these requirements, provide a JSON response with:
    1. Complexity level (low/medium/high)
    2. Business logic rules that should be implemented

    Complexity Guidelines:
    - LOW: Simple CRUD operations, basic display features
    - MEDIUM: Moderate business logic, some validations, basic integrations
    - HIGH: Complex business rules, security requirements, external integrations, compliance needs

    Return ONLY a JSON object in this format:
    {
      "complexity": "low|medium|high",
      "logicRules": [
        "Business rule 1 based on requirements",
        "Business rule 2 based on requirements",
        "Business rule 3 based on requirements"
      ]
    }
    `;

    const message = await anthropic.messages.create({
      model: "claude-3-5-sonnet-20241022",
      max_tokens: 1000,
      temperature: 0.1,
      messages: [{ role: "user", content: prompt }]
    });

    // Parse the response
    const responseText = message.content[0].text.trim();
    console.log('🧠 AI Raw Response:', responseText);
    
    
    
    // Extract JSON from response
    const jsonMatch = responseText.match(/\{[\s\S]*\}/);
    if (!jsonMatch) {
      throw new Error('Invalid AI response format');
    }

    const analysis = JSON.parse(jsonMatch[0]);
    console.log('✅ AI Analysis Result:', analysis);

    return {
      complexity: analysis.complexity || 'medium',
      logicRules: analysis.logicRules || []
    };

  } catch (error) {
    console.error('❌ AI Analysis failed:', error);
    
    // Fallback analysis
    return {
      complexity: 'medium',
      logicRules: ['Users must be authenticated to access this feature']
    };
  }
};
