#!/usr/bin/env node
/* eslint-disable @typescript-eslint/no-require-imports */

const { spawn } = require('child_process');
const path = require('path');

const originalCwd = process.cwd();

// Change working directory to the package root directory so next start can resolve built pages (.next)
const packageRoot = path.join(__dirname, '..');
process.chdir(packageRoot);

// Next.js provides a cli entry point in next/dist/bin/next
const nextBin = require.resolve('next/dist/bin/next');

console.log("🚀 Starting NeuralLoom AI Orchestrator dashboard...");
console.log("🔗 Open http://localhost:3000 in your browser to begin.");

const nextProcess = spawn(process.execPath, [nextBin, 'start', '-p', '3000'], {
  stdio: 'inherit',
  env: {
    ...process.env,
    ORIGINAL_CWD: originalCwd
  }
});

// Clean up child process on exit signals
process.on('SIGINT', () => {
  nextProcess.kill('SIGINT');
  process.exit();
});

process.on('SIGTERM', () => {
  nextProcess.kill('SIGTERM');
  process.exit();
});

nextProcess.on('error', (err) => {
  console.error('Failed to start NeuralLoom server:', err);
});
