import { Router, Request, Response } from 'express';
import { cacheMiddleware } from '../middleware/cache';
import {
  buildProofIndex,
  getLatestReserveCapacitySnapshot,
  refreshReserveCapacityCache,
} from '../../services/gru-reserve-capacity';

const router = Router();

/**
 * GET /reserve/capacity — semi-public live reserve capacity + multi-point proof quorum.
 * Public (no OMNL API key). Cached 10s; ?refresh=1 forces recompute when live scheduler enabled.
 */
router.get('/reserve/capacity', cacheMiddleware(10 * 1000), async (req: Request, res: Response) => {
  try {
    const forceRefresh = req.query.refresh === '1';
    let snapshot = getLatestReserveCapacitySnapshot();
    const maxAgeSec = snapshot?.sla?.freshnessMaxAgeSeconds ?? 60;
    const stale =
      !snapshot ||
      (Date.now() - new Date(snapshot.generatedAt).getTime()) / 1000 > maxAgeSec;

    if (forceRefresh || stale) {
      snapshot = await refreshReserveCapacityCache(
        String(req.query.set || process.env.GRU_RESERVE_CAPACITY_MINIMUM_SET || 'reserveCapacityLive'),
      );
    }

    if (!snapshot) {
      res.status(503).json({
        error: 'Reserve capacity snapshot unavailable',
        hint: 'Enable GRU_RESERVE_CAPACITY_LIVE=1 or run pnpm gru:reserve-capacity:collect',
      });
      return;
    }

    res.setHeader('Cache-Control', 'public, max-age=10, stale-while-revalidate=30');
    res.setHeader('X-GRU-Proof-Quorum', snapshot.proofQuorum.passed ? 'pass' : 'fail');
    res.status(200).json(snapshot);
  } catch (e) {
    const msg = e instanceof Error ? e.message : String(e);
    res.status(500).json({ error: msg });
  }
});

/**
 * GET /reserve/proof-index — status of all configured proof points (P1–P7).
 */
router.get('/reserve/proof-index', cacheMiddleware(15 * 1000), (_req: Request, res: Response) => {
  res.setHeader('Cache-Control', 'public, max-age=15');
  res.json(buildProofIndex());
});

export default router;
