import express from 'express';
import { ScreenshotCache } from './cache.js';
import { takeScreenshot, closeBrowser } from './screenshot.js';

const PORT = parseInt(process.env.PORT || '8002', 10);
const NARROWIT_URL = process.env.NARROWIT_URL || 'http://localhost:8001';
const CACHE_DIR = process.env.CACHE_DIR || '/cache';

const cache = new ScreenshotCache(CACHE_DIR);
const app = express();

app.get('/health', (_req, res) => {
  res.status(200).send('ok');
});

app.get('/screenshot', async (req, res) => {
  try {
    const params: Record<string, string> = {};
    for (const key of ['v', 'f', 'poi', 'tab']) {
      const val = req.query[key];
      if (typeof val === 'string' && val) {
        params[key] = val;
      }
    }

    const cacheKey = cache.buildKey(params);

    // Check cache first
    const cached = cache.get(cacheKey);
    if (cached) {
      res.setHeader('Content-Type', 'image/png');
      res.setHeader('Cache-Control', 'public, max-age=86400');
      res.setHeader('X-Cache', 'HIT');
      cached.pipe(res);
      return;
    }

    // Build the URL for the frontend in screenshot mode
    const qs = new URLSearchParams(params);
    qs.set('screenshot', '1');
    const url = `${NARROWIT_URL}/?${qs}`;

    console.log(`Taking screenshot: ${url}`);
    const png = await takeScreenshot(url);

    // Cache it
    cache.set(cacheKey, png);

    res.setHeader('Content-Type', 'image/png');
    res.setHeader('Cache-Control', 'public, max-age=86400');
    res.setHeader('X-Cache', 'MISS');
    res.send(png);
  } catch (err) {
    console.error('Screenshot failed:', err);
    res.status(500).json({ error: 'Screenshot failed' });
  }
});

const server = app.listen(PORT, () => {
  console.log(`OG screenshot service listening on port ${PORT}`);
  console.log(`  NARROWIT_URL: ${NARROWIT_URL}`);
  console.log(`  CACHE_DIR: ${CACHE_DIR}`);
});

// Graceful shutdown
for (const signal of ['SIGTERM', 'SIGINT']) {
  process.on(signal, async () => {
    console.log(`Received ${signal}, shutting down...`);
    server.close();
    await closeBrowser();
    process.exit(0);
  });
}
