const express = require('express');
const router = express.Router();
const axios = require('axios');
const config = require('../config');

router.post('/', async (req, res) => {
  const prompt = req.body.prompt ? req.body.prompt.trim() : '';
  const model = req.body.model || 'google/gemini-2.5-flash-image';
  
  if (!prompt) return res.status(400).json({ error: 'Prompt is required' });
  
  try {
    if (model.startsWith('pollinations')) {
      await generatePollinations(prompt, model, res);
    } else if (['free', 'flux-free', 'seedream'].includes(model)) {
      await generateFreeSVG(prompt, res);
    } else if (model.startsWith('google/')) {
      await generateViaGemini(prompt, model, res);
    } else {
      await generateViaOpenRouter(prompt, model, res);
    }
  } catch (err) {
    res.status(502).json({ error: err.message });
  }
});

async function generatePollinations(prompt, model, res) {
  const seed = Math.floor(Math.random() * 2147483647);
  const encoded = encodeURIComponent(prompt);
  let pollModel = 'turbo';
  if (model === 'pollinations-flux') pollModel = 'flux';
  else if (model === 'pollinations-flux-realism') pollModel = 'flux-realism';
  else if (model === 'pollinations-flux-pro') pollModel = 'flux-pro';
  
  const imageUrl = `https://image.pollinations.ai/prompt/${encoded}?width=1024&height=1024&model=${pollModel}&nologo=true&seed=${seed}&enhance=true`;
  res.json({ data: [{ url: imageUrl }] });
}

async function generateFreeSVG(prompt, res) {
  const svgPrompt = 'Generate ONLY valid SVG code. Make a beautiful, detailed SVG image of: ' + prompt + '. Return ONLY raw SVG markup starting with <svg and ending with </svg>. No HTML, no markdown, no explanation.';
  try {
    const response = await axios.post('https://openrouter.ai/api/v1/chat/completions', {
      model: 'openrouter/free',
      messages: [{ role: 'user', content: svgPrompt }],
      max_tokens: 2000
    }, {
      headers: { 'Authorization': `Bearer ${config.OPENROUTER_API_KEY}` }
    });
    let svg = response.data.choices[0].message.content || '';
    svg = svg.replace(/^.*?(<svg)/s, '$1').replace(/(<\/svg>).*$/s, '$1');
    if (svg.includes('<svg')) {
      const b64 = Buffer.from(svg).toString('base64');
      return res.json({ data: [{ url: `data:image/svg+xml;base64,${b64}` }] });
    }
    res.status(503).json({ error: 'Free service: no SVG tag in response' });
  } catch (err) {
    res.status(503).json({ error: 'Free service error: ' + err.message });
  }
}

async function generateViaOpenRouter(prompt, model, res) {
  try {
    const response = await axios.post('https://openrouter.ai/api/v1/chat/completions', {
      model: model,
      messages: [{ role: 'user', content: prompt }],
      max_tokens: 200
    }, {
      headers: { 'Authorization': `Bearer ${config.OPENROUTER_API_KEY}` }
    });
    
    const choice = response.data.choices[0].message || {};
    const images = [];
    if (choice.images) {
      choice.images.forEach(img => {
        if (img.image_url && img.image_url.url) images.push({ url: img.image_url.url });
      });
    }
    if (choice.content_parts) {
      choice.content_parts.forEach(part => {
        if (part.type === 'image_url' && part.image_url && part.image_url.url) images.push({ url: part.image_url.url });
      });
    }
    res.json({ data: images });
  } catch (err) {
    res.status(502).json({ error: 'Image generation failed: ' + (err.response?.data?.error?.message || err.message) });
  }
}

async function generateViaGemini(prompt, model, res) {
  const m = model.replace('google/', '');
  let googleModel = 'gemini-2.5-flash-image'; // Simplify mapping for Node version
  const url = `https://generativelanguage.googleapis.com/v1beta/models/${googleModel}:generateContent?key=${config.GEMINI_API_KEY}`;
  
  try {
    const response = await axios.post(url, {
      contents: [{ parts: [{ text: prompt }] }],
      generationConfig: { responseModalities: ['Text', 'Image'] }
    });
    
    const images = [];
    const candidates = response.data.candidates || [];
    candidates.forEach(c => {
      (c.content.parts || []).forEach(p => {
        if (p.inlineData && p.inlineData.data) {
          images.push({ url: `data:${p.inlineData.mimeType};base64,${p.inlineData.data}` });
        }
      });
    });
    
    if (images.length > 0) return res.json({ data: images });
    
    let text = candidates[0]?.content?.parts?.[0]?.text || '';
    if (text) {
      let svg = text.replace(/^.*?(<svg)/s, '$1').replace(/(<\/svg>).*$/s, '$1');
      if (svg.includes('<svg')) {
        const b64 = Buffer.from(svg).toString('base64');
        return res.json({ data: [{ url: `data:image/svg+xml;base64,${b64}` }] });
      }
    }
    res.status(503).json({ error: 'Gemini: no image generated' });
  } catch (err) {
    if (err.response?.status === 429) {
      return res.status(429).json({ error: 'Gemini: Quota exceeded.' });
    }
    res.status(502).json({ error: 'Gemini: ' + (err.response?.data?.error?.message || err.message) });
  }
}

module.exports = router;
