#!/usr/bin/env node
/**
 * Post-install splash for `npm i -g madarx`.
 *
 * Prints the madarX wordmark, runs a short animated sequence over REAL read-only
 * checks (no fake sleeps, no side effects — it never creates the data home or
 * touches the DB), and closes on a framed next-steps panel.
 *
 * Guards (an install must NEVER fail or spam because of a splash):
 *   - skips entirely on non-TTY, NO_COLOR, CI, or MADARX_NO_SPLASH=1
 *   - skips when madarx is installed as a dependency of another package
 *     (only the top-level / global install gets the splash)
 *   - wraps everything; any error exits 0 so `npm install` is never broken
 */

import path from 'node:path';
import fs from 'node:fs';
import { fileURLToPath } from 'node:url';

const PKG_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');

function shouldSkip() {
  // Force bypass for the `npm run splash` preview (renders regardless of TTY/global).
  if (process.env.MADARX_FORCE_SPLASH === '1') return false;
  if (process.env.MADARX_NO_SPLASH === '1') return true;
  if (process.env.NO_COLOR) return true;
  if (process.env.CI) return true;
  if (!process.stdout || !process.stdout.isTTY) return true;
  // Only the global install (`npm i -g madarx`) gets the splash. A local/dev
  // `npm install` in the checkout, or a transitive dep install, stays silent —
  // npm sets npm_config_global=true only for `-g`.
  if (process.env.npm_config_global !== 'true') return true;
  return false;
}

async function main() {
  if (shouldSkip()) return;

  // Lazy import so a skipped run does zero work and pulls no ANSI machinery.
  const { wordmark, fg, _palette: P } = await import('../lib/cli/banner.js');
  const { bootSequence, dateline } = await import('../lib/cli/splash.js');

  let version = '0.0.0';
  try { version = JSON.parse(fs.readFileSync(path.join(PKG_ROOT, 'package.json'), 'utf8')).version || version; } catch {}

  const home = process.env.MADARX_HOME
    || (process.env.HOME ? path.join(process.env.HOME, '.madarx') : '~/.madarx');

  // $ install context line (Muted), then the wordmark + Muted subtitle.
  console.log();
  console.log('  ' + fg(P.muted, '$ npm i -g madarx'));
  console.log();
  console.log(wordmark());
  console.log();
  console.log('  ' + fg(P.muted, 'local-first agent runtime'));
  console.log();

  // Honest, read-only checks — the spinner spins over genuine work, never a
  // timer; nothing here creates the data home or opens the DB (setup does that).
  await bootSequence([
    { label: 'Resolving madarX from npm registry', work: async () => true /* npm just did */ },
    {
      label: `Verifying Node ${process.version}  (node:sqlite needs ≥ 22.5)`,
      work: async () => {
        const [maj, min] = process.versions.node.split('.').map(Number);
        if (maj < 22 || (maj === 22 && min < 5)) throw new Error('Node >= 22.5 required');
      },
    },
    { label: 'Locating prebuilt web tier  .next/standalone', work: async () => fs.existsSync(path.join(PKG_ROOT, '.next', 'standalone', 'server.js')) },
    { label: 'Registering engines  claude-code · anthropic · ollama · codex · hermes', work: async () => fs.existsSync(path.join(PKG_ROOT, 'lib', 'agent-engines.js')) },
    { label: `Data home  ${home}`, work: async () => fs.existsSync(home) /* read-only; setup creates it */ },
    { label: 'Linking  madarx  CLI → lib/cli', work: async () => fs.existsSync(path.join(PKG_ROOT, 'bin', 'madarx.mjs')) },
  ]).catch(() => { /* a failed check still shows ✗; never break the install */ });

  console.log();
  console.log('  ' + fg(P.muted, 'run') + ' ' + fg(P.mars, 'madarx setup') + ' ' + fg(P.muted, 'to configure, then') + ' ' + fg(P.mars, 'madarx') + ' ' + fg(P.muted, 'to launch'));
  console.log('  ' + dateline(version));
  console.log();
}

main().catch(() => {}).finally(() => process.exit(0));
