/**
 * config/discoveryTestMode.js
 *
 * If NCII_DEEP_DISCOVERY_TEST_MODE=1, deepDiscovery.runCaseScan skips
 * the real Scrape.do Google calls and feeds a fixed candidate list
 * straight into validation + RDAP + production_pending. This proves
 * the full pipeline (queue → worker → validate → discover → RDAP →
 * persist → admin "Send all" → audit JSON) without burning any
 * Scrape.do quota.
 *
 * It also starts a local HTTP server on a random port that serves
 * crafted HTML for the fixture's "leak site" URLs. The crafted HTML
 * includes the victim's name + an NCII keyword in close proximity,
 * plus a working <img> tag. This way the validation gate passes and
 * the site gets promoted all the way through to production_pending.
 *
 * The fixture is in scripts/fixtures/discovery-candidates.json. It is
 * intentionally a mix of "leak site" URLs (served by the local test
 * server — should be promoted), real public domains that will fail
 * the name+NCII co-occurrence check (filtered as FPs), and broken
 * URLs (should fail validation as "no such host").
 */

'use strict';

const fs   = require('fs');
const path = require('path');
const http = require('http');

const isTestMode = () => process.env.NCII_DEEP_DISCOVERY_TEST_MODE === '1';

function loadFixture() {
  const p = path.join(__dirname, '..', 'scripts', 'fixtures', 'discovery-candidates.json');
  if (!fs.existsSync(p)) {
    console.warn('[discoveryTestMode] fixture missing:', p, '— discovery will run with 0 candidates');
    return [];
  }
  try {
    return JSON.parse(fs.readFileSync(p, 'utf8'));
  } catch (e) {
    console.warn('[discoveryTestMode] fixture parse error:', e.message);
    return [];
  }
}

let _server = null;
let _port   = null;
let _token  = null;

function startTestServer() {
  if (_server) return { port: _port, token: _token };
  _token = 'ncii-test-' + Math.random().toString(36).slice(2, 10);
  _server = http.createServer((req, res) => {
    if (req.headers['x-test-token'] !== _token && req.url.startsWith('/img/')) {
      res.writeHead(403); res.end(); return;
    }
    if (req.url.startsWith('/img/')) {
      // 1x1 transparent PNG
      const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=', 'base64');
      res.writeHead(200, { 'content-type': 'image/png', 'content-length': png.length });
      res.end(png);
      return;
    }
    const filler = '\n'.repeat(20) + '<p>' + 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. '.repeat(15) + '</p>\n';
    const html = `<!doctype html><html lang="en"><head><title>Test leak site — Nisali Siriwardene</title>
<meta name="description" content="synthetic test fixture" />
<style>body{font-family:sans-serif;max-width:900px;margin:2rem auto;padding:0 1rem;}</style>
</head>
<body>
  <h1>Test NCII content</h1>
  <p>This is a fake leak page used to exercise the deep discovery pipeline.
  The victim's name "Nisali Siriwardene" appears here in close proximity
  to NCII keywords like "nude" and "leaked" within 140 characters,
  so the co-occurrence validator should pass.</p>
  <img src="/img/photo1.png" alt="leaked photo" />
  <img src="/img/photo2.png" alt="more leaked photos" />
  <p>Full text: leaked nude photos of Nisali Siriwardene are circulating
  online. This is a synthetic test fixture — there are no real NCII images
  on this page.</p>
  ${filler}
  <footer>test fixture</footer>
</body></html>`;
    res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'content-length': Buffer.byteLength(html) });
    res.end(html);
  });
  _server.listen(0, '127.0.0.1', () => {
    _port = _server.address().port;
    console.log(`[discoveryTestMode] test HTTP server on http://127.0.0.1:${_port} (token=${_token})`);
  });
  return new Promise((resolve) => {
    _server.once('listening', () => resolve({ port: _port, token: _token }));
    if (_port) resolve({ port: _port, token: _token });
  });
}

function stopTestServer() {
  if (_server) { _server.close(); _server = null; _port = null; _token = null; }
}

function injectTestUrls(fixture, port, token) {
  return fixture.map((r, i) => {
    if (r.url && r.url.startsWith('test://leak/')) {
      return { ...r, url: `http://127.0.0.1:${port}${r.url.replace('test://leak', '')}` };
    }
    return r;
  });
}

function getTestTokenHeader() {
  return _token ? { 'x-test-token': _token } : {};
}

module.exports = { isTestMode, loadFixture, startTestServer, stopTestServer, injectTestUrls, getTestTokenHeader };
