#!/usr/bin/env node

/**
 * Managed Development Server
 * 
 * This script manages the Next.js development server with proper process handling
 * and pre-compilation of TypeScript modules for immediate responsiveness.
 */

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

console.log('🚀 Starting Managed Development Server...');

// Pre-compile TypeScript modules first
console.log('🔄 Step 1: Pre-compiling TypeScript modules...');

const precompileProcess = spawn('node', ['scripts/precompile-modules.js'], {
    stdio: 'inherit',
    cwd: process.cwd()
});

precompileProcess.on('close', (code) => {
    if (code === 0) {
        console.log('✅ Pre-compilation completed successfully');
        startDevServer();
    } else {
        console.log('⚠️  Pre-compilation completed with warnings, proceeding...');
        startDevServer();
    }
});

precompileProcess.on('error', (error) => {
    console.log('⚠️  Pre-compilation error:', error.message);
    console.log('🔄 Proceeding with development server...');
    startDevServer();
});

function startDevServer() {
    console.log('🚀 Step 2: Starting Next.js development server...');
    
    const devServer = spawn('npx', ['next', 'dev', '--port', '3000', '--hostname', '0.0.0.0'], {
        stdio: 'inherit',
        cwd: process.cwd()
    });
    
    // Handle graceful shutdown
    process.on('SIGINT', () => {
        console.log('\n🛑 Received SIGINT, shutting down gracefully...');
        devServer.kill('SIGTERM');
        process.exit(0);
    });
    
    process.on('SIGTERM', () => {
        console.log('\n🛑 Received SIGTERM, shutting down gracefully...');
        devServer.kill('SIGTERM');
        process.exit(0);
    });
    
    devServer.on('error', (error) => {
        console.error('💥 Development server error:', error);
        process.exit(1);
    });
    
    devServer.on('close', (code) => {
        console.log(`🏁 Development server exited with code ${code}`);
        process.exit(code);
    });
}
