#!/usr/bin/env node
import { existsSync, readFileSync } from 'node:fs';
import { spawnSync } from 'node:child_process';
import path from 'node:path';

const command = process.argv[2];
if (!command) {
  console.error('[react-path] Missing command argument (e.g. lint/test/build/dev).');
  process.exit(1);
}

const reactDir = path.resolve(process.cwd(), 'frontend-react');
const reactPkgPath = path.join(reactDir, 'package.json');
const reactNodeModulesPath = path.join(reactDir, 'node_modules');

if (!existsSync(reactPkgPath)) {
  console.log(`[react-path] Stub: frontend-react is not scaffolded yet. Skipping "${command}".`);
  process.exit(0);
}

const reactPkg = JSON.parse(readFileSync(reactPkgPath, 'utf8'));
if (!reactPkg.scripts || !reactPkg.scripts[command]) {
  console.log(`[react-path] Stub: frontend-react/package.json has no "${command}" script. Skipping.`);
  process.exit(0);
}

if (!existsSync(reactNodeModulesPath)) {
  console.log('[react-path] Stub: frontend-react dependencies are not installed. Skipping.');
  process.exit(0);
}

const result = spawnSync('npm', ['--prefix', reactDir, 'run', command], {
  stdio: 'inherit',
});

if (typeof result.status === 'number') {
  process.exit(result.status);
}

process.exit(1);
