import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { safeFetch, safeFetchText, getFetchMetrics } from '../apis/utils/fetch.mjs';

test('safeFetch reports HTML as degraded JSON response', async () => {
  const originalFetch = globalThis.fetch;
  globalThis.fetch = async () => ({
    ok: true,
    status: 200,
    headers: { get: () => 'text/html' },
    text: async () => '<html>not json</html>',
  });
  try {
    const data = await safeFetch('https://example.test/json', { retries: 0, source: 'unit' });
    assert.match(data.error, /Expected JSON/);
    assert.ok(getFetchMetrics().bySource.unit.requests >= 1);
  } finally {
    globalThis.fetch = originalFetch;
  }
});

test('safeFetchText returns text and byte count', async () => {
  const originalFetch = globalThis.fetch;
  globalThis.fetch = async () => ({
    ok: true,
    status: 200,
    text: async () => 'hello',
  });
  try {
    const data = await safeFetchText('https://example.test/rss', { retries: 0, source: 'rss-unit' });
    assert.equal(data.text, 'hello');
    assert.equal(data.bytes, 5);
  } finally {
    globalThis.fetch = originalFetch;
  }
});

test('scenario watchlist feature is wired into sweep, briefing, and dashboard', () => {
  const scenarios = readFileSync(new URL('../lib/scenarios.mjs', import.meta.url), 'utf8');
  const server = readFileSync(new URL('../server.mjs', import.meta.url), 'utf8');
  const html = readFileSync(new URL('../dashboard/public/jarvis.html', import.meta.url), 'utf8');
  const readme = readFileSync(new URL('../README.md', import.meta.url), 'utf8');
  assert.match(scenarios, /DEFAULT_SCENARIOS/);
  assert.match(scenarios, /runsDir, 'scenarios\.json'/);
  assert.match(scenarios, /scenario-state\.json/);
  assert.match(scenarios, /watching.*building.*confirmed/s);
  assert.match(server, /evaluateScenarios\(synthesized, delta, RUNS_DIR\)/);
  assert.match(server, /\*Scenario Watchlist\*/);
  assert.match(html, /Scenario Watchlist/);
  assert.match(readme, /runs\/scenarios\.json/);
});
