const express = require('express'); const puppeteer = require('puppeteer'); const cors = require('cors'); const app = express(); app.use(cors()); app.use(express.json({ limit: '10mb' })); app.post('/api/render', async (req, res) => { const { data } = req.body; if (!data || !data.items) { return res.status(400).json({ error: 'Missing analysis data' }); } const { items, total, health_score, confidence, tip, insights } = data; let scoreEmoji = '🟢'; if (health_score < 50) scoreEmoji = '🔴'; else if (health_score < 80) scoreEmoji = '🟡'; // Build items HTML const itemsHtml = items.map(it => `
${it.name || 'Desconhecido'}
${it.portion || 'N/A'}
${Math.round(it.calories || 0)} kcal
`).join(''); // Build insights HTML let insightsHtml = ''; if (insights && insights.length > 0) { insightsHtml = `
VEREDITO DA IA
`; } // Beautiful Instagram-like Card HTML const html = `
FoodSnap AI
Score Nutricional: ${health_score || 0}/100 ${scoreEmoji}
${Math.round(total.calories || 0)}
Kcal
${confidence === 'high' ? '98%' : '85%'}
Precisão IA
Proteínas
${total.protein || 0}g
Carboidratos
${total.carbs || 0}g
Gorduras
${total.fat || 0}g
${insightsHtml}
O QUE A IA IDENTIFICOU
${itemsHtml} ${tip && tip.text ? `
💡 Insight do Nutricionista IA
${tip.text}
` : ''}
`; try { const browser = await puppeteer.launch({ args: ['--no-sandbox', '--disable-setuid-sandbox'], headless: "new" }); const page = await browser.newPage(); await page.setViewport({ width: 1080, height: 1080, deviceScaleFactor: 2 }); await page.setContent(html, { waitUntil: 'networkidle0' }); // Wait for fonts to load implicitly or network idle const element = await page.$('#capture'); const buffer = await element.screenshot({ type: 'png' }); await browser.close(); res.set('Content-Type', 'image/png'); res.send(buffer); } catch (err) { console.error("Puppeteer render error:", err); res.status(500).json({ error: 'Failed to generate image' }); } }); const PORT = process.env.PORT || 3001; app.listen(PORT, () => { console.log("Image Renderer active on port", PORT); });