#!/usr/bin/env node
import { spawn } from 'node:child_process';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const [command, variant, ...rawArgs] = process.argv.slice(2);

if (!command || !variant) {
  console.error('Usage: node scripts/run-with-variant.mjs <command> <variant> [-- <next args...>]');
  process.exit(1);
}

const allowedVariants = new Set(['frontend', 'full']);
if (!allowedVariants.has(variant)) {
  console.error(`Unknown build variant '${variant}'. Use one of: ${Array.from(allowedVariants).join(', ')}`);
  process.exit(1);
}

const separatorIndex = rawArgs.indexOf('--');
const nextArgs = separatorIndex === -1 ? rawArgs : rawArgs.slice(separatorIndex + 1);

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const nextBin = path.join(__dirname, '..', 'node_modules', '.bin', 'next');

const env = {
  ...process.env,
  FUNNEL_BUILD_VARIANT: variant,
  NEXT_PUBLIC_FUNNEL_BUILD_VARIANT: variant,
};

const child = spawn(nextBin, [command, ...nextArgs], {
  stdio: 'inherit',
  env,
  shell: process.platform === 'win32',
});

child.on('exit', (code, signal) => {
  if (typeof code === 'number') {
    process.exit(code);
  }
  process.kill(process.pid, signal ?? 'SIGTERM');
});
