#!/usr/bin/env node
// neruva-record-hook -- platform-detecting wrapper for the native Rust binary
//
// Bundled binaries (one per platform) live in ../binaries/. This wrapper
// picks the right one based on process.platform + process.arch, exec's it
// with stdin/stdout/stderr inherited, and exits with the child's exit code.
//
// Cost vs direct native call: ~50-100ms Node cold start. Still ~10x faster
// than the Python hook fallback. For latency-critical setups, point
// settings.json directly at binaries/neruva-record-hook-<plat>-<arch>[.exe]
// to skip the Node wrapper entirely.
//
// On chmod-required platforms (POSIX), the postinstall script makes the
// right binary executable. If the binary isn't present or isn't executable,
// we exit 0 silently (Claude Code keeps running; the user just doesn't get
// the auto-pilot block this turn).

import { spawn } from 'node:child_process';
import { dirname, join } from 'node:path';
import { existsSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { platform, arch } from 'node:os';

const __dirname = dirname(fileURLToPath(import.meta.url));

function pickBinary() {
  const p = platform();
  const a = arch();
  const platSeg =
    p === 'win32' ? 'win'
    : p === 'darwin' ? 'mac'
    : 'linux';
  const archSeg = a === 'arm64' ? 'arm64' : 'x64';
  const ext = p === 'win32' ? '.exe' : '';
  return join(__dirname, '..', 'binaries', `neruva-record-hook-${platSeg}-${archSeg}${ext}`);
}

const binary = pickBinary();

if (!existsSync(binary)) {
  // Silent fallback -- never block Claude Code. User can re-install
  // @neruva/mcp or check that the postinstall ran (chmod +x on POSIX).
  process.exit(0);
}

const child = spawn(binary, process.argv.slice(2), {
  stdio: 'inherit',
});

child.on('error', () => process.exit(0));
child.on('exit', (code) => process.exit(code ?? 0));
