import { spawn } from 'child_process';

// Clear screen initially for a fresh launch log
console.clear();
console.log('\x1b[31m%s\x1b[0m', '🚀 Launching Laravilt Dev Suite (Vite + Laravel Serve)...');

const child = spawn('npx', [
    'concurrently',
    '-k',
    '--names', 'vite,laravel',
    '-c', 'blue.bold,red.bold',
    '"vite --host 0.0.0.0"',
    '"php artisan serve --host=0.0.0.0 --port=8000"'
], {
    stdio: 'inherit',
    shell: true
});

let isExiting = false;

// We intercept exit signals on parent but do not call process.exit() immediately.
// This allows the child process to finish its exit sequence and printing first.
process.on('SIGINT', () => {
    isExiting = true;
});

process.on('SIGTERM', () => {
    isExiting = true;
    child.kill('SIGTERM');
});

// The final cleanup and screen clear is handled only when the child process has completely closed.
// This prevents any residual child exit logs from printing after the screen is cleared.
child.on('exit', () => {
    setTimeout(() => {
        console.clear();
        process.exit(0);
    }, 100); // 100ms grace period to ensure console output buffers are fully flushed
});
