#!/usr/bin/env node
// CJS shim that runs before the ESM bundle to fail fast on unsupported Node.
// Kept in CJS so the parse step uses only Node ≥0.x APIs — this file must
// load cleanly even on the Node versions we are about to reject.
'use strict';

const { checkNodeVersion, formatBanner } = require('./check-node.cjs');

const result = checkNodeVersion(process.versions.node);

if (!result.ok) {
  process.stderr.write(formatBanner(result.detected));
  // 64 = EX_USAGE per BSD sysexits — "the command was used incorrectly".
  // Distinct from 1 (generic), 2 (pleri-not-configured), 3 (pull failed),
  // 4 (protocol mismatch), 5 (auth); see packages/cli/src/exit-codes.ts.
  process.exit(64);
}

// Fast-path `--version` / `-V` BEFORE loading the ESM bundle (issue #988).
// Fresh-user installs run `olam --version` as the install-script sanity
// check; any hang in the bundle's import graph (better-sqlite3 native probe,
// agentmemory MCP context-loader, Dockerode lazy-binding) would block this
// path indefinitely. Reading package.json directly from the CJS shim
// guarantees `--version` returns in <100ms regardless of bundle state.
const argv = process.argv.slice(2);
if (argv.length === 1 && (argv[0] === '--version' || argv[0] === '-V')) {
  try {
    const fs = require('node:fs');
    const path = require('node:path');
    const pkgPath = path.join(__dirname, '..', 'package.json');
    const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
    process.stdout.write(`${pkg.version || '0.0.0-unknown'}\n`);
    process.exit(0);
  } catch (err) {
    // Fall through to the bundle if the fast-path read fails for any reason
    // (corrupt package.json, missing file). The bundle's own readCliVersion
    // has the same fallback chain and will print '0.0.0-unknown' if needed.
  }
}

const { join } = require('node:path');
const { pathToFileURL } = require('node:url');
const bundlePath = join(__dirname, '..', 'dist', 'index.js');

import(pathToFileURL(bundlePath).href).catch((err) => {
  process.stderr.write(`olam: failed to load CLI bundle (${bundlePath})\n  ${err && err.message ? err.message : err}\n`);
  process.exit(1);
});
