import http from 'http';

function parseEnabled(value, defaultValue = true) {
  if (value === undefined || value === null || value === '') {
    return defaultValue;
  }
  const normalized = String(value).trim().toLowerCase();
  if (['0', 'false', 'no', 'off'].includes(normalized)) {
    return false;
  }
  if (['1', 'true', 'yes', 'on'].includes(normalized)) {
    return true;
  }
  return defaultValue;
}

function getHost() {
  return String(process.env.RELAY_HEALTH_HOST || '0.0.0.0').trim() || '0.0.0.0';
}

function getPort() {
  const raw = parseInt(process.env.RELAY_HEALTH_PORT || '9860', 10);
  return Number.isFinite(raw) && raw > 0 ? raw : 9860;
}

export async function startRelayHealthServer(relayService, logger) {
  if (!parseEnabled(process.env.RELAY_HEALTH_ENABLED, true)) {
    logger.info('Relay health server disabled by RELAY_HEALTH_ENABLED');
    return null;
  }

  const host = getHost();
  const port = getPort();
  const server = http.createServer((req, res) => {
    const path = String(req.url || '').split('?')[0];

    if (req.method !== 'GET') {
      res.writeHead(405, { 'content-type': 'application/json; charset=utf-8' });
      res.end(JSON.stringify({ ok: false, error: 'method_not_allowed' }));
      return;
    }

    if (path !== '/health' && path !== '/healthz' && path !== '/status') {
      res.writeHead(404, { 'content-type': 'application/json; charset=utf-8' });
      res.end(JSON.stringify({ ok: false, error: 'not_found' }));
      return;
    }

    const payload = relayService.getHealthSnapshot();
    res.writeHead(200, {
      'cache-control': 'no-store',
      'content-type': 'application/json; charset=utf-8'
    });
    res.end(JSON.stringify(payload));
  });

  return await new Promise((resolve) => {
    let resolved = false;
    const settle = (value) => {
      if (!resolved) {
        resolved = true;
        resolve(value);
      }
    };

    server.on('error', (error) => {
      logger.error('Relay health server error:', error);
      settle(null);
    });

    server.listen(port, host, () => {
      logger.info(`Relay health server listening on http://${host}:${port}/healthz`);
      settle(server);
    });
  });
}
