#!/usr/bin/env node
// Robust launcher for omnius CLI.
// - Runs the ESM entry as a child process
// - On exit code 120 (update), resets terminal and restarts child
// - Prevents raw-mode/mouse-tracking bleedthrough on restart or crash

const { spawn, spawnSync } = require('node:child_process');
const { resolve } = require('node:path');

function resetTerminal() {
  try { if (process.stdin.isTTY && typeof process.stdin.setRawMode === 'function') process.stdin.setRawMode(false); } catch {}
  // Disable mouse tracking, bracketed paste, show cursor, reset attrs, exit alt screen if active
  const ESC = '\x1B';
  try {
    process.stdout.write(
      ESC + '[?25h' +             // show cursor
      ESC + '[?1000l' +           // X10 mouse off
      ESC + '[?1002l' +           // button-event mouse off
      ESC + '[?1003l' +           // any-event mouse off
      ESC + '[?1006l' +           // SGR mouse off
      ESC + '[?1015l' +           // urxvt mouse off
      ESC + '[?2004l' +           // bracketed paste off
      ESC + '[?1049l' +           // exit alt screen
      ESC + '[0m'                 // reset attributes
    );
  } catch {}
  // stty sane (POSIX)
  if (process.platform !== 'win32' && process.stdin.isTTY) {
    try { spawnSync('stty', ['sane'], { stdio: 'inherit' }); } catch {}
  }
}

function runChild() {
  const entry = resolve(__dirname, 'index.js');
  const args = [entry, ...process.argv.slice(2)];
  const child = spawn(process.execPath, args, {
    stdio: 'inherit',
    env: process.env,
  });
  return child;
}

(async () => {
  let restarts = 0;
  const MAX_RESTARTS = 3;
  let child = runChild();

  const forward = (sig) => {
    try { child && child.kill(sig); } catch {}
  };
  process.on('SIGINT', () => forward('SIGINT'));
  process.on('SIGTERM', () => forward('SIGTERM'));

  function attach(childProc) {
    childProc.on('exit', (code, signal) => {
      if (signal) {
        resetTerminal();
        process.kill(process.pid, signal);
        return;
      }
      if (code === 120 && restarts < MAX_RESTARTS) {
        // Update-triggered restart
        resetTerminal();
        restarts += 1;
        setTimeout(() => {
          child = runChild();
          attach(child);
        }, 300);
        return;
      }
      // Normal exit or too many restarts
      resetTerminal();
      process.exit(typeof code === 'number' ? code : 0);
    });
  }

  attach(child);
})();
