// tests/uat/a6.test.ts — Plan 01-13 standalone A6 entry point.
//
// Refactored in Wave 2 to use the shared `tests/uat/lib/` scaffolding
// (`launchHarnessBrowser`, `driveA6`, `runAssertion`, `printAssertionResult`).
// Behavior-preserving: A6 still PASSES 5/5 in ~7s end-to-end. The ~80
// LoC of Chrome-launch + console-attach + result-print plumbing
// previously inlined here now lives in `tests/uat/lib/{launch,assertions,
// harness-page-driver}.ts` — single source of truth for Wave 3's 13
// additional assertions.
//
// This standalone entry is RETAINED throughout the rest of Plan 01-13
// for fast TDD iteration on the A6 contract:
//   `npx tsx tests/uat/a6.test.ts`           # headless, ~7s
//   `HEADLESS=0 npx tsx tests/uat/a6.test.ts`  # interactive debug view
//
// The orchestrator-level entry `npm run test:uat` (lands in Wave 3A)
// runs all 14 assertions (~60-90s); this single-A6 entry is for the
// inner loop when iterating on Bug B fix verification or harness-page
// surface changes.
//
// Pre-flight: requires `dist-test/` from `npm run build:test`. The
// `assertBundlePresent` call inside `launchHarnessBrowser` fails
// loudly if the bundle is missing.

import { launchHarnessBrowser } from './lib/launch';
import { driveA6 } from './lib/harness-page-driver';
import { runAssertion, printAssertionResult } from './lib/assertions';

/**
 * Standalone A6 driver entry point.
 *
 * @returns Process exit code: 0 on PASS, 1 on FAIL.
 */
async function main(): Promise<number> {
  process.stdout.write('\nMokosh Plan 01-13 — A6 (Bug B canonical) standalone driver\n');
  process.stdout.write('Architecture: extension-internal page + bridge + synthetic stream\n');
  process.stdout.write('='.repeat(72) + '\n');

  const handles = await launchHarnessBrowser();
  process.stdout.write(`Extension id: ${handles.extensionId}\n`);
  process.stdout.write(`Downloads dir: ${handles.downloadsDir}\n`);
  process.stdout.write('Harness page ready; invoking assertA6()...\n\n');

  let exitCode = 1;
  try {
    const result = await runAssertion(
      'A6 — BUG B canonical: user-stopped-sharing routes via setIdleMode',
      () => driveA6(handles.harnessPage),
      { swConsole: handles.swConsole, offConsole: handles.offConsole },
    );
    printAssertionResult(result);
    exitCode = result.passed ? 0 : 1;
  } catch (err) {
    process.stderr.write(`\n*** Top-level harness error: ${String(err)}\n`);
    exitCode = 1;
  } finally {
    try {
      await handles.browser.close();
    } catch (closeErr) {
      process.stderr.write(`(non-fatal: browser close threw: ${String(closeErr)})\n`);
    }
  }

  return exitCode;
}

const code = await main();
process.exit(code);
