const express = require('express');
const cors = require('cors');
const axios = require('axios');

const app = express();
const PORT = process.env.PORT || 8009;

// Claude API configuration
const CLAUDE_API_KEY = process.env.CLAUDE_API_KEY || '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';
const CLAUDE_AVAILABLE = !!CLAUDE_API_KEY;

// Middleware
app.use(cors({
  origin: "*",
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization', 'X-User-ID', 'X-User-Role']
}));
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true }));

// Health check endpoint
app.get('/health', (req, res) => {
  res.status(200).json({
    status: 'healthy',
    service: 'template-manager-ai',
    version: '1.0.0',
    timestamp: new Date().toISOString(),
    uptime: process.uptime(),
    features: {
      ai_analysis: true
    }
  });
});

// AI Feature Analysis endpoint
app.post('/api/analyze-feature', async (req, res) => {
  try {
    console.log('🤖 [Template Manager AI] AI Analysis request received');
    
    const { featureName, description, requirements = [], projectType } = req.body;
    
    // Ensure requirements is always an array
    const safeRequirements = Array.isArray(requirements) ? requirements : [];
    
    console.log('📋 [Template Manager AI] Analyzing feature:', featureName);
    console.log('📋 [Template Manager AI] Project type:', projectType);
    console.log('📋 [Template Manager AI] Requirements:', safeRequirements);
    
    let analysis;
    
    // Try Claude AI first if available
    if (CLAUDE_AVAILABLE) {
      try {
        console.log('🤖 [Template Manager AI] Using Claude AI for analysis...');
        analysis = await analyzeWithClaude(featureName, description, safeRequirements, projectType);
      } catch (claudeError) {
        console.warn('⚠️ [Template Manager AI] Claude AI failed, falling back to rule-based analysis:', claudeError.message);
        analysis = await analyzeWithRules(featureName, description, safeRequirements, projectType);
      }
    } else {
      console.log('📋 [Template Manager AI] Using rule-based analysis (Claude not available)');
      analysis = await analyzeWithRules(featureName, description, safeRequirements, projectType);
    }
    
    console.log('✅ [Template Manager AI] Analysis completed:', analysis.complexity, 'complexity');
    
    res.json({
      success: true,
      analysis: analysis
    });
    
  } catch (error) {
    console.error('❌ [Template Manager AI] AI Analysis error:', error);
    res.status(500).json({
      success: false,
      error: error.message,
      message: 'AI analysis failed'
    });
  }
});

// Claude AI Analysis function
async function analyzeWithClaude(featureName, description, requirements, projectType) {
  const safeRequirements = Array.isArray(requirements) ? requirements : [];
  const requirementsText = safeRequirements.length > 0 ? safeRequirements.map(req => `- ${req}`).join('\n') : 'No specific requirements provided';
  
  const prompt = `Analyze this custom feature for a ${projectType || 'web application'} project:

Feature Name: ${featureName || 'Custom Feature'}
Description: ${description || 'No description provided'}

Detailed Requirements:
${requirementsText}

Based on these requirements, provide a detailed analysis in JSON format:
{
  "feature_name": "Improved technical name",
  "complexity": "low|medium|high",
  "logicRules": ["Business rule 1", "Business rule 2", "Business rule 3"],
  "implementation_details": ["Technical detail 1", "Technical detail 2", "Technical detail 3"],
  "technical_requirements": ["Requirement 1", "Requirement 2", "Requirement 3"], 
  "estimated_effort": "1-2 weeks|2-3 weeks|3-4 weeks|4+ weeks",
  "dependencies": ["Dependency 1", "Dependency 2"],
  "api_endpoints": ["POST /api/endpoint1", "GET /api/endpoint2"],
  "database_tables": ["table1", "table2"],
  "confidence_score": 0.85
}

For complexity assessment:
- "low": Simple CRUD, basic features, minimal business logic
- "medium": Moderate business logic, some integrations, standard features
- "high": Complex business rules, external integrations, security requirements, real-time features

For logicRules, generate specific business rules based on the requirements like:
- Access control and authorization rules
- Data validation and business logic rules  
- Workflow and process rules
- Security and compliance requirements

Return ONLY the JSON object, no other text.`;

  try {
    const response = await axios.post('https://api.anthropic.com/v1/messages', {
      model: 'claude-3-5-sonnet-20241022',
      max_tokens: 2000,
      temperature: 0.1,
      messages: [{ role: 'user', content: prompt }]
    }, {
      headers: {
        'x-api-key': CLAUDE_API_KEY,
        'Content-Type': 'application/json',
        'anthropic-version': '2023-06-01'
      }
    });

    const responseText = response.data.content[0].text.trim();
    
    // Extract JSON from response
    const jsonMatch = responseText.match(/\{[\s\S]*\}/);
    if (jsonMatch) {
      const analysis = JSON.parse(jsonMatch[0]);
      console.log('✅ [Template Manager AI] Claude analysis successful');
      return analysis;
    } else {
      throw new Error('No valid JSON found in Claude response');
    }
  } catch (error) {
    console.error('❌ [Template Manager AI] Claude API error:', error.message);
    throw error;
  }
}

// Rule-based analysis function
async function analyzeWithRules(featureName, description, requirements, projectType) {
  const complexity = analyzeComplexity(description, requirements);
  const logicRules = generateLogicRules(featureName, description, requirements, projectType);
  
  return {
    feature_name: featureName || 'Custom Feature',
    complexity: complexity,
    logicRules: logicRules,
    implementation_details: [
      `Implement ${featureName || 'Custom Feature'} with proper validation`,
      'Add error handling and logging',
      'Include unit and integration tests'
    ],
    technical_requirements: [
      'Database schema design',
      'API endpoint implementation', 
      'Frontend component development'
    ],
    estimated_effort: complexity === 'high' ? '3-4 weeks' : complexity === 'low' ? '1-2 weeks' : '2-3 weeks',
    dependencies: ['User authentication', 'Database setup'],
    api_endpoints: [
      `POST /api/${(featureName || 'custom-feature').toLowerCase().replace(/\s+/g, '-')}`,
      `GET /api/${(featureName || 'custom-feature').toLowerCase().replace(/\s+/g, '-')}`
    ],
    database_tables: [`${(featureName || 'custom_feature').toLowerCase().replace(/\s+/g, '_')}_table`],
    confidence_score: 0.75
  };
}

// Helper function to analyze complexity
function analyzeComplexity(description, requirements) {
  const safeRequirements = Array.isArray(requirements) ? requirements : [];
  const text = `${description || ''} ${safeRequirements.join(' ')}`.toLowerCase();
  
  const highComplexityKeywords = ['encryption', 'hipaa', 'compliance', 'security', 'integration', 'real-time', 'ai', 'machine learning', 'blockchain', 'payment', 'transaction'];
  const mediumComplexityKeywords = ['crud', 'database', 'api', 'authentication', 'validation', 'search', 'filter', 'workflow', 'approval'];
  const lowComplexityKeywords = ['display', 'show', 'view', 'list', 'basic', 'simple'];
  
  if (highComplexityKeywords.some(keyword => text.includes(keyword))) {
    return 'high';
  } else if (mediumComplexityKeywords.some(keyword => text.includes(keyword))) {
    return 'medium';
  } else if (lowComplexityKeywords.some(keyword => text.includes(keyword))) {
    return 'low';
  }
  
  return 'medium'; // default
}

// Helper function to generate logic rules
function generateLogicRules(featureName, description, requirements, projectType) {
  const rules = [];
  const safeRequirements = Array.isArray(requirements) ? requirements : [];
  const text = `${description || ''} ${safeRequirements.join(' ')}`.toLowerCase();
  
  // Project type specific rules
  if (projectType?.toLowerCase() === 'healthcare') {
    rules.push('Only authorized caregivers can access patient data');
    rules.push('All patient data access must be logged for HIPAA compliance');
    rules.push('Patient data must be encrypted at rest and in transit');
  }
  
  if (projectType?.toLowerCase() === 'ecommerce') {
    rules.push('Payment information must be PCI DSS compliant');
    rules.push('Order status updates must be real-time');
    rules.push('Inventory levels must be validated before purchase');
  }
  
  // Feature specific rules
  if (text.includes('crud') || text.includes('manage')) {
    rules.push('Users can only modify data they have created or been granted access to');
  }
  
  if (text.includes('patient') || text.includes('medical')) {
    rules.push('Patient information can only be accessed by assigned caregivers');
    rules.push('All patient data modifications require audit trail');
  }
  
  if (text.includes('payment') || text.includes('transaction')) {
    rules.push('All financial transactions must be logged and auditable');
    rules.push('Payment processing must include fraud detection');
  }
  
  if (text.includes('approval') || text.includes('workflow')) {
    rules.push('Approval workflows must have configurable escalation rules');
    rules.push('All approval decisions must be logged with timestamps');
  }
  
  // Generic rules
  if (rules.length === 0) {
    rules.push('Data validation must be performed on all inputs');
    rules.push('User permissions must be checked before data access');
    rules.push('All operations must be logged for audit purposes');
  }
  
  return rules;
}

// Root endpoint
app.get('/', (req, res) => {
  res.json({
    message: 'Template Manager AI Service - AI Feature Analysis',
    version: '1.0.0',
    endpoints: {
      health: '/health',
      ai_analysis: '/api/analyze-feature'
    }
  });
});

// Error handling middleware
app.use((err, req, res, next) => {
  console.error('❌ Error:', err.stack);
  res.status(500).json({
    error: 'Internal Server Error',
    message: process.env.NODE_ENV === 'development' ? err.message : 'Something went wrong'
  });
});

// 404 handler
app.use('*', (req, res) => {
  res.status(404).json({
    error: 'Not Found',
    message: `Route ${req.originalUrl} not found`
  });
});

// Start server
app.listen(PORT, '0.0.0.0', () => {
  console.log('🚀 Template Manager AI Service started');
  console.log(`📡 Server running on http://0.0.0.0:${PORT}`);
  console.log('🏥 Health check: http://0.0.0.0:8009/health');
  console.log('🤖 AI Analysis endpoint: http://0.0.0.0:8009/api/analyze-feature');
  console.log('🎯 AI Feature Analysis ready!');
});
