'use strict';

const express = require('express');

function buildHealthRoutes(opts) {
  const { state, proxyRegistry, startedAt } = opts;
  const router = express.Router();

  function memMb() {
    return Math.round(process.memoryUsage().rss / 1024 / 1024);
  }

  router.get('/healthz', (req, res) => {
    const stats = proxyRegistry.stats();
    const rssMb = memMb();
    const status = rssMb > 1024 ? 'degraded' : 'ok';
    res.json({
      status,
      uptime: Math.round((Date.now() - startedAt) / 1000),
      bots: state.activeBots.size,
      proxies: stats,
      memory: { rssMb },
    });
  });

  router.get('/metrics', (req, res) => {
    const stats = proxyRegistry.stats();
    const rss = process.memoryUsage().rss;
    const lines = [];
    lines.push(`# HELP crackedflooder_bots_active Number of currently active bots`);
    lines.push(`# TYPE crackedflooder_bots_active gauge`);
    lines.push(`crackedflooder_bots_active ${state.activeBots.size}`);
    lines.push(`# HELP crackedflooder_bots_spawned_total Total bots ever spawned`);
    lines.push(`# TYPE crackedflooder_bots_spawned_total counter`);
    lines.push(`crackedflooder_bots_spawned_total ${state.counters.totalBotsSpawned}`);
    lines.push(`# HELP crackedflooder_bots_failed_total Total bot failures`);
    lines.push(`# TYPE crackedflooder_bots_failed_total counter`);
    lines.push(`crackedflooder_bots_failed_total ${state.counters.totalConnectionsFailed}`);
    lines.push(`# HELP crackedflooder_handshakes_ok_total Total successful handshakes`);
    lines.push(`# TYPE crackedflooder_handshakes_ok_total counter`);
    lines.push(`crackedflooder_handshakes_ok_total ${state.counters.totalHandshakesOk}`);
    lines.push(`# HELP crackedflooder_keepalives_total Total keep-alives sent`);
    lines.push(`# TYPE crackedflooder_keepalives_total counter`);
    lines.push(`crackedflooder_keepalives_total ${state.counters.totalKeepAlivesSent}`);
    lines.push(`# HELP crackedflooder_proxy_alive Alive proxies`);
    lines.push(`# TYPE crackedflooder_proxy_alive gauge`);
    lines.push(`crackedflooder_proxy_alive ${stats.alive}`);
    lines.push(`# HELP crackedflooder_proxy_dead Dead proxies`);
    lines.push(`# TYPE crackedflooder_proxy_dead gauge`);
    lines.push(`crackedflooder_proxy_dead ${stats.dead}`);
    lines.push(`# HELP crackedflooder_proxy_score_avg Average proxy score`);
    lines.push(`# TYPE crackedflooder_proxy_score_avg gauge`);
    lines.push(`crackedflooder_proxy_score_avg ${stats.avgScore}`);
    lines.push(`# HELP crackedflooder_proxy_p50_latency_ms P50 proxy latency`);
    lines.push(`# TYPE crackedflooder_proxy_p50_latency_ms gauge`);
    lines.push(`crackedflooder_proxy_p50_latency_ms ${stats.p50Latency}`);
    lines.push(`# HELP crackedflooder_proxy_p95_latency_ms P95 proxy latency`);
    lines.push(`# TYPE crackedflooder_proxy_p95_latency_ms gauge`);
    lines.push(`crackedflooder_proxy_p95_latency_ms ${stats.p95Latency}`);
    lines.push(`# HELP crackedflooder_node_rss_bytes Process RSS in bytes`);
    lines.push(`# TYPE crackedflooder_node_rss_bytes gauge`);
    lines.push(`crackedflooder_node_rss_bytes ${rss}`);
    res.type('text/plain; version=0.0.4').send(lines.join('\n') + '\n');
  });

  router.get('/diagnostics', (req, res) => {
    res.json({
      uptime: Math.round((Date.now() - startedAt) / 1000),
      bots: state.activeBots.size,
      proxyStats: proxyRegistry.stats(),
      memory: process.memoryUsage(),
      counters: state.counters,
    });
  });

  return router;
}

module.exports = { buildHealthRoutes };
