#!/usr/bin/env node
// Pings every admin-console route against a running dev server.
// Asserts HTTP 200 and that the body looks like rendered HTML.
// Exits 1 on the first failure; reports a final summary on success.
//
// Usage:
//   1. In one terminal: `npm run dev`  (server on http://127.0.0.1:8787)
//   2. In another:      `npm run smoke:routes`
//
// Override the base URL with MADARX_SMOKE_BASE_URL.

const BASE_URL = process.env.MADARX_SMOKE_BASE_URL || 'http://127.0.0.1:8787';
const TIMEOUT_MS = 10_000;

// Mirrors the sidebar navigation in app/components/ui/sidebar-with-submenu.jsx
// plus Help, Settings, and Runtime (linked from /help). Keep in sync if the
// sidebar grows.
const ROUTES = [
  '/',
  '/projects',
  '/agents',
  '/tasks',
  '/approvals',
  '/disk',
  '/missions',
  '/audit',
  '/schedules',
  '/activity',
  '/reports',
  '/marketplace',
  '/help',
  '/settings',
  '/runtime',
];

async function probe(path) {
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);
  const url = `${BASE_URL}${path}`;
  const started = Date.now();
  try {
    const res = await fetch(url, {
      headers: { 'user-agent': 'madarx-smoke/1.0' },
      signal: controller.signal,
      redirect: 'follow',
    });
    const body = await res.text();
    const elapsed = Date.now() - started;
    return {
      path,
      url,
      status: res.status,
      ok: res.ok && body.includes('<html'),
      bytes: body.length,
      ms: elapsed,
    };
  } catch (err) {
    return {
      path,
      url,
      status: 0,
      ok: false,
      error: err.message || String(err),
      ms: Date.now() - started,
    };
  } finally {
    clearTimeout(timer);
  }
}

async function main() {
  console.log(`[smoke] ${ROUTES.length} routes against ${BASE_URL}`);
  const results = [];
  for (const path of ROUTES) {
    const result = await probe(path);
    results.push(result);
    const tag = result.ok ? 'OK ' : 'FAIL';
    const detail = result.ok
      ? `${result.status} · ${result.bytes}b · ${result.ms}ms`
      : `${result.status || 'no-response'} · ${result.error || 'body missing <html>'} · ${result.ms}ms`;
    console.log(`  ${tag}  ${result.path.padEnd(14)}  ${detail}`);
  }

  const failures = results.filter((r) => !r.ok);
  console.log('');
  if (failures.length === 0) {
    console.log(`[smoke] ${results.length}/${results.length} routes passed`);
    process.exit(0);
  } else {
    console.log(`[smoke] ${failures.length}/${results.length} routes failed`);
    for (const f of failures) {
      console.log(`  ${f.path}: ${f.error || `status ${f.status}`}`);
    }
    console.log('');
    console.log('Hint: make sure `npm run dev` is running on the expected port.');
    process.exit(1);
  }
}

main().catch((err) => {
  console.error('[smoke] unexpected error:', err);
  process.exit(2);
});
