const pool = require('../config/db');
const https = require('https');

class AIService {
  get apiKey() { return process.env.GEMINI_API_KEY || ''; }
  get model() { return 'gemini-1.5-flash'; }

  isEnabled() { return this.apiKey.length > 10; }

  async analyzeTicket(ticketId) {
    if (!this.isEnabled()) return null;
    const [tickets] = await pool.query('SELECT * FROM tickets WHERE id=?', [ticketId]);
    if (!tickets.length) return null;
    const t = tickets[0];

    const [articles] = await pool.query("SELECT title, LEFT(content,200) as excerpt FROM kb_articles WHERE status='published' LIMIT 8");
    const kb = articles.map(a => `- ${a.title}: ${a.excerpt}`).join('\n');

    const prompt = `Eres un asistente ITSM experto. Analiza este ticket de soporte técnico. Responde SOLO JSON válido, sin backticks ni markdown.
TICKET: Asunto: ${t.subject} | Descripción: ${t.description} | Prioridad actual: ${t.priority}
BASE DE CONOCIMIENTO:\n${kb}
Responde con este JSON exacto: {"priority_suggestion":"low|medium|high|critical","summary":"resumen en 2 líneas","suggested_response":"respuesta profesional sugerida en español","urgency_detected":true/false,"kb_article":"título artículo relacionado o null","confidence":0.8}`;

    const text = await this.callGemini(prompt);
    if (!text) return null;
    try {
      return JSON.parse(text.replace(/```json?\s*/g, '').replace(/```/g, '').trim());
    } catch { return null; }
  }

  async suggestResponse(ticketId) {
    if (!this.isEnabled()) return null;
    const [tickets] = await pool.query('SELECT subject, description FROM tickets WHERE id=?', [ticketId]);
    if (!tickets.length) return null;
    const [comments] = await pool.query('SELECT c.comment, u.name FROM ticket_comments c JOIN users u ON c.user_id=u.id WHERE c.ticket_id=? ORDER BY c.created_at', [ticketId]);
    const history = comments.map(c => `${c.name}: ${c.comment}`).join('\n');
    const prompt = `Eres un agente de soporte técnico profesional. Sugiere una respuesta empática y profesional en español para este ticket.
Asunto: ${tickets[0].subject}
Descripción: ${tickets[0].description}
${history ? 'Historial de conversación:\n' + history : 'No hay conversación previa.'}
Responde SOLO con el texto de la respuesta sugerida, sin explicaciones adicionales.`;
    return this.callGemini(prompt);
  }

  callGemini(prompt) {
    return new Promise((resolve) => {
      const payload = JSON.stringify({
        contents: [{ parts: [{ text: prompt }] }],
        generationConfig: { temperature: 0.3, maxOutputTokens: 1024 }
      });

      const options = {
        hostname: 'generativelanguage.googleapis.com',
        path: `/v1beta/models/${this.model}:generateContent?key=${this.apiKey}`,
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Content-Length': Buffer.byteLength(payload)
        },
        timeout: 25000
      };

      const req = https.request(options, (res) => {
        let data = '';
        res.on('data', chunk => data += chunk);
        res.on('end', () => {
          try {
            if (res.statusCode !== 200) {
              console.error('Gemini API error:', res.statusCode, data.substring(0, 300));
              return resolve(null);
            }
            const json = JSON.parse(data);
            resolve(json.candidates?.[0]?.content?.parts?.[0]?.text || null);
          } catch (e) {
            console.error('Gemini parse error:', e.message);
            resolve(null);
          }
        });
      });

      req.on('error', (e) => {
        console.error('Gemini connection error:', e.message);
        resolve(null);
      });

      req.on('timeout', () => {
        console.error('Gemini timeout');
        req.destroy();
        resolve(null);
      });

      req.write(payload);
      req.end();
    });
  }
}

module.exports = new AIService();
