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-preview-image';
  
  if (!prompt) return res.status(400).json({ error: 'Prompt is required' });
  
  if (model.startsWith('google/')) {
    await generateViaGemini(prompt, model, res);
  } else {
    res.status(400).json({ error: 'Unsupported model: ' + model });
  }
});

async function generateViaGemini(prompt, model, res) {
  let m = model.replace('google/', '').replace(/-image$/, '').replace('-preview', '');
  let googleModel = m;
  if (m === 'gemini-2.5-flash') googleModel = 'gemini-2.5-flash-preview-05-08';
  else if (m === 'gemini-2.0-flash-exp') googleModel = 'gemini-2.0-flash-exp-image-generation';
  
  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 media generated' });
  } catch (err) {
    res.status(502).json({ error: 'Gemini: ' + (err.response?.data?.error?.message || err.message) });
  }
}

module.exports = router;
