const OpenAI = require('openai');
const db = require('../db');

class AiService {
  constructor() {
    this.openai = null;
  }

  async init() {
    try {
        const result = await db.query("SELECT value FROM system_settings WHERE `key` = 'ai_api_key'");
        // Handle potential JSON wrapping if value was stored with JSON.stringify
        let apiKey = result.rows[0]?.value;

        if (apiKey) {
            // Remove quotes if they exist (sometimes JSON strings are stored with quotes)
            if (apiKey.startsWith('"') && apiKey.endsWith('"')) {
                apiKey = apiKey.slice(1, -1);
            }
            this.openai = new OpenAI({ apiKey });
        } else {
            console.warn('AiService: OpenAI API Key not found in system_settings.');
        }
    } catch (error) {
        console.error('AiService: Failed to initialize.', error);
    }
  }

  async generateBlogContent(newsItem, techContext = null, matchingLabs = []) {
    if (!this.openai) await this.init();
    if (!this.openai) throw new Error('OpenAI not initialized (Missing API Key)');

    const contentSource = newsItem.fullContent || newsItem.contentSnippet || newsItem.content || 'Analysis of recent security events.';
    
    // Format lab context if available
    const labContext = matchingLabs.length > 0 
        ? matchingLabs.map(l => `- [PROPOSED LAB] ${l.title} (${l.type === 'operation' ? 'SOC Simulation' : 'Academy Module'})`).join('\n')
        : "N/A";

    const prompt = `
      You are a Senior Threat Intelligence Analyst at "InfoSecLabs".
      Your goal is to transform raw technical data into a professional "Threat Intelligence Report".

      TOPIC: "${newsItem.title}"
      
      TECHNICAL CONTEXT (Extracted Research):
      ${techContext ? JSON.stringify(techContext, null, 2) : "Use source data for research."}

      SOURCE DATA: """
      ${contentSource}
      """

      RELATED TRAINING CONTENT (Integrate these in the Simulation Context section):
      ${labContext}

      --------------------------------------------------
      STYLE GUIDE:
      - **Length**: MINIMUM 1500 WORDS.
      - **Tone**: Authoritative, technically precise, expert-to-expert.
      - **Branding**: ALWAYS use "InfoSecLabs".
      --------------------------------------------------
      STRUCTURE:
      1. **Executive Briefing**: Strategic overview (Actor, Impact, Exploit).
      2. **Technical Deep Dive**: Chain of execution, payloads, realistic log/terminal examples. Use the Extracted Research for precision.
      3. **🛡️ Detection & Response**: Specific log sources, P1-P3 severity, and a technical Hunt Query.
      4. **🎓 Academy Focus**: Career impact and technical glossary.
      5. **🚀 Lab Integration**: Link the topic to our related training (Mention the Proprosed Labs identified above).
      6. **MITRE ATT&CK® Mapping**: Precise Techniques from research.

      Use Standard Github-Flavored Markdown.
    `;

    try {
        const completion = await this.openai.chat.completions.create({
          messages: [{ role: "system", content: "You are a professional Cyber Threat Intelligence writer." }, { role: "user", content: prompt }],
          model: "gpt-4-turbo",
          temperature: 0.7,
        });

        return completion.choices[0].message.content;
    } catch (error) {
        console.error("OpenAI Blog Gen Error:", error);
        throw error;
    }
  }

    async generateBlogImage(title) {
        if (!this.openai) await this.init();
        if (!this.openai) throw new Error('OpenAI not initialized');

        // Enhanced prompt for consistent, text-free, professional images
        const prompt = `
      High-end, photorealistic cybersecurity concept art for the topic: "${title}".
      
      Style Requirements:
      - Futuristic, Cyberpunk, High-Tech, Dark Mode aesthetic.
      - Neon accents (Cyan, Purple, Electric Blue) on dark backgrounds.
      - Abstract representation of the concept (e.g., if ransomware, show digital locks or encrypted data streams, NOT a hacker in a hoodie).
      - Professional, clean, suitable for a corporate tech blog.
      - 3D Render style, Octane Render, Unreal Engine 5 quality.
      
      NEGATIVE PROMPT (STRICTLY FORBIDDEN):
      - NO TEXT. NO WORDING. NO LETTERS. NO LABELS.
      - No cheesy hacker stock photos.
      - No messy or cluttered compositions.
    `;

        try {
            const response = await this.openai.images.generate({
                model: "dall-e-3",
                prompt: prompt,
                n: 1,
                size: "1792x1024",
                quality: "standard",
                style: "vivid"
            });

            return response.data[0].url;
        } catch (error) {
            console.error("DALL-E Blog Image Error:", error);
            // Fallback or re-throw
            throw error;
        }
    }

    async generateGeminiImagePrompt(title) {
        // Return a high-quality prompt for the user to use in Gemini
        return `
---
### 🎨 Gemini Image Generation Prompt
**Topic**: ${title}

**Prompt**:
> "Create a high-end, photorealistic cybersecurity concept art for: '${title}'. Use a futuristic, cyberpunk, high-tech dark mode aesthetic with neon accents (cyan, purple, electric blue). The composition should be an abstract representation of the technical concept (avoid hackers in hoodies or text) however if it is about OSs you can add some icons or it is about cyber attacks you can add some icons about cyber attacks. 3D Render style, Octane Render quality, 16:9 aspect ratio. NO TEXT, NO LETTERS."
---
`;
    }
  async extractTechnicalContext(content) {
    if (!this.openai) await this.init();
    if (!this.openai) throw new Error('OpenAI not initialized');

    const prompt = `
      Analyze the following cybersecurity news content and extract technical metadata in JSON format.
      
      CONTENT:
      """
      ${content}
      """
      
      OUTPUT FORMAT (JSON ONLY):
      {
        "cves": ["CVE-XXXX-XXXX"],
        "mitre_ttps": [{"id": "TXXXX", "name": "Technique Name"}],
        "threat_actors": ["APT Group Name"],
        "affected_products": ["Product Name"],
        "key_technical_terms": ["Keyword1", "Keyword2"],
        "summary": "One sentence technical summary."
      }
    `;

    try {
        const completion = await this.openai.chat.completions.create({
          messages: [{ role: "system", content: "You are a Cyber Threat Intelligence extractor. Output JSON only." }, { role: "user", content: prompt }],
          model: "gpt-4-turbo",
          response_format: { type: "json_object" }
        });

        return JSON.parse(completion.choices[0].message.content);
    } catch (error) {
        console.error("AI Context Extraction Error:", error);
        return null;
    }
  }

  async findMatchingLabs(techContext) {
    try {
        // Collect search terms
        const searchTerms = [
            ...(techContext.mitre_ttps || []).map(t => t.name),
            ...(techContext.key_technical_terms || []),
            ...(techContext.threat_actors || [])
        ].filter(Boolean);

        if (searchTerms.length === 0) return [];

        // Build a query to search across operations and learning paths
        // We look for keyword matches in titles and descriptions
        let matches = [];
        
        for (const term of searchTerms.slice(0, 5)) { // Limit to top 5 terms for efficiency
            const termQuery = `%${term}%`;
            
            // Search Operations
            const ops = await db.query(
                "SELECT id, title, 'operation' as type FROM operations WHERE (title LIKE ? OR description LIKE ?) AND is_active = 1 LIMIT 2",
                [termQuery, termQuery]
            );
            matches.push(...ops.rows);

            // Search Learning Paths/Modules
            const paths = await db.query(
                "SELECT id, title, 'academy' as type FROM learning_paths WHERE (title LIKE ? OR description LIKE ?) AND is_active = 1 LIMIT 2",
                [termQuery, termQuery]
            );
            matches.push(...paths.rows);
        }

        // De-duplicate matches by id/type
        const uniqueMatches = [];
        const seen = new Set();
        for (const m of matches) {
            const key = `${m.type}-${m.id}`;
            if (!seen.has(key)) {
                seen.add(key);
                uniqueMatches.push(m);
            }
        }

        return uniqueMatches.slice(0, 3); // Return top 3 unique matches
    } catch (error) {
        console.error("Lab Matching Error:", error);
        return [];
    }
  }

  async refineSeoMetadata(content, title) {
    if (!this.openai) await this.init();
    if (!this.openai) {
        return {
            seoTitle: title.substring(0, 60),
            seoDescription: content.substring(0, 150).replace(/<[^>]*>/g, ''),
            focusKeyword: title.split(' ')[0]
        };
    }

    console.log('🧠 AI Service: Refining SEO Metadata...');
    const prompt = `
        Act as a Senior SEO Specialist. Analyze the following blog content and title, and provide highly optimized SEO metadata.
        
        Content: ${content.substring(0, 5000)}
        Current Title: ${title}
        
        Return ONLY a JSON object with:
        {
            "seoTitle": "Optimized Page Title (max 60 chars)",
            "seoDescription": "Compelling meta description (max 160 chars)",
            "focusKeyword": "Primary long-tail keyword"
        }
    `;

    try {
        const response = await this.openai.chat.completions.create({
            model: "gpt-4-turbo-preview",
            messages: [{ role: "user", content: prompt }],
            response_format: { type: "json_object" }
        });

        return JSON.parse(response.choices[0].message.content);
    } catch (error) {
        console.error('refineSeoMetadata Error:', error);
        // Fallback
        return {
            seoTitle: title.substring(0, 60),
            seoDescription: content.substring(0, 150).replace(/<[^>]*>/g, ''),
            focusKeyword: title.split(' ')[0]
        };
    }
  }
}

module.exports = new AiService();
