const express = require('express');
const multer = require('multer');
const { recognizeImage } = require('./ocr');

const app = express();
const upload = multer({ storage: multer.memoryStorage(), limits: { fileSize: 10 * 1024 * 1024 } });
const port = Number(process.env.PORT || 4010);

app.use(express.json({ limit: '10mb' }));

app.get('/health', (_req, res) => {
  res.json({ ok: true });
});

app.post('/ocr/forecast', upload.single('image'), async (req, res) => {
  try {
    const imageBuffer = req.file?.buffer || null;

    if (!imageBuffer) {
      return res.status(400).json({
        error: 'Provide multipart field image'
      });
    }

    const result = await recognizeImage({
      imageBuffer
    });

    return res.json({
      rawForecast: result.rawForecast,
      forecast: result.forecast,
      cached: result.cached
    });
  } catch (error) {
    return res.status(500).json({
      error: error.message
    });
  }
});

app.listen(port, () => {
  console.log(`Forecast OCR service listening on port ${port}`);
});
