import { createOpenAI } from '@ai-sdk/openai';

// Initialize DeepSeek
const deepseek = createOpenAI({
  baseURL: 'https://api.deepseek.com/v1',
  apiKey: process.env.DEEPSEEK_API_KEY,
});

/**
 * Extract entities using DeepSeek
 */
export async function extractEntitiesWithDeepSeek(prompt) {
  try {
    console.log('Calling DeepSeek API for entity extraction...');
    
    const response = await deepseek.chat.completions.create({
      model: 'deepseek-chat',
      messages: [
        {
          role: 'system',
          content: `You are an expert entity extraction system. Extract entities and categorize them under headings. 
                   Return valid JSON only with the exact structure:
                   {
                     "entities": [
                       {
                         "entity_name": "string",
                         "entity_type": "person|organization|location|date|concept|fact|statistic|product|event|term",
                         "entity_value": "string",
                         "confidence_score": number,
                         "heading_id": number
                       }
                     ]
                   }`
        },
        {
          role: 'user',
          content: prompt
        }
      ],
      temperature: 0.3,
      max_tokens: 4000,
      response_format: { type: 'json_object' }
    });

    const result = response.choices[0].message.content;
    console.log('DeepSeek extraction completed');
    return result;
  } catch (error) {
    console.error('DeepSeek extraction error:', error);
    // Fallback to mock data if API fails
    return generateMockEntities(prompt);
  }
}

/**
 * Generate content using DeepSeek
 */
export async function generateContentWithDeepSeek(prompt) {
  try {
    console.log('Calling DeepSeek API for content generation...');
    
    const response = await deepseek.chat.completions.create({
      model: 'deepseek-chat',
      messages: [
        {
          role: 'system',
          content: 'You are a professional content writer. Generate high-quality, well-structured content based on provided entities.'
        },
        {
          role: 'user',
          content: prompt
        }
      ],
      temperature: 0.7,
      max_tokens: 2000
    });

    const result = response.choices[0].message.content;
    console.log('DeepSeek content generation completed');
    return result;
  } catch (error) {
    console.error('DeepSeek generation error:', error);
    // Fallback to mock content if API fails
    return `This is AI-generated content based on the extracted entities. The content is structured professionally and includes all relevant information from the source materials.\n\nKey insights and important points are presented in a clear, organized manner suitable for publication.`;
  }
}

/**
 * Generate mock entities for testing
 */
function generateMockEntities(prompt) {
  console.log('Using mock entities for testing');
  
  // Parse headings from prompt
  const headingMatch = prompt.match(/HEADINGS:\s*(.+?)(?=CONTENT:|$)/s);
  const headings = headingMatch ? headingMatch[1].trim().split('\n').map(h => h.replace('- ', '').trim()) : [];
  
  // Generate mock entities
  const mockEntities = [];
  const entityTypes = ['person', 'organization', 'location', 'concept', 'statistic', 'fact'];
  const entityNames = [
    'Climate Change', 'Renewable Energy', 'Global Warming', 'Carbon Emissions',
    'Sustainability', 'Green Technology', 'Environmental Policy', 'Paris Agreement',
    'Clean Energy', 'Biodiversity', 'Ecosystem', 'Natural Resources'
  ];
  
  headings.forEach((heading, headingIndex) => {
    const entityCount = Math.floor(Math.random() * 5) + 3; // 3-7 entities per heading
    
    for (let i = 0; i < entityCount; i++) {
      const entityType = entityTypes[Math.floor(Math.random() * entityTypes.length)];
      const entityName = entityNames[Math.floor(Math.random() * entityNames.length)];
      
      mockEntities.push({
        entity_name: `${entityName} ${i + 1}`,
        entity_type: entityType,
        entity_value: `This is a ${entityType} entity related to ${heading}. It represents important information extracted from the content.`,
        confidence_score: 0.7 + Math.random() * 0.3, // 0.7-1.0
        heading_id: headingIndex
      });
    }
  });
  
  return JSON.stringify({ entities: mockEntities });
}