'use strict';

const { spawnSync } = require('child_process');

const npmExecPath = process.env.npm_execpath;
if (!npmExecPath) {
  console.error('No se pudo detectar npm_execpath. Ejecuta este script desde npm: npm run build:node22');
  process.exit(1);
}

const args = process.argv.slice(2);
if (!args.length) {
  console.error('Uso: node scripts/run-with-node22.js <npm-script>');
  process.exit(1);
}

const npx = process.platform === 'win32' ? 'npx.cmd' : 'npx';
const result = process.platform === 'win32'
  ? spawnSync(`${npx} -y -p node@22 node "${npmExecPath}" run ${args.join(' ')}`, {
      stdio: 'inherit',
      shell: true,
    })
  : spawnSync(npx, ['-y', '-p', 'node@22', 'node', npmExecPath, 'run', ...args], {
      stdio: 'inherit',
      shell: false,
    });

if (result.error) {
  console.error(result.error.message);
  process.exit(1);
}

process.exit(result.status || 0);
