#!/usr/bin/env node

/**
 * Development server with hot reload for SmartSolTech
 * Uses nodemon for automatic server restart on file changes
 */

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

// Configuration
const SERVER_FILE = path.join(__dirname, '..', 'server.js');
const NODEMON_CONFIG = {
    script: SERVER_FILE,
    ext: 'js,json,ejs',
    ignore: ['node_modules/', 'public/', '.git/'],
    watch: ['models/', 'routes/', 'views/', 'server.js'],
    env: {
        NODE_ENV: 'development',
        DEBUG: 'app:*'
    },
    delay: 1000
};

function startDevelopmentServer() {
    console.log('🚀 Starting SmartSolTech development server...');
    console.log('📁 Watching files for changes...');
    console.log('🔄 Server will automatically restart on file changes');
    console.log('');

    const nodemonArgs = [
        NODEMON_CONFIG.script,
        '--ext', NODEMON_CONFIG.ext,
        '--ignore', NODEMON_CONFIG.ignore.join(','),
        '--watch', NODEMON_CONFIG.watch.join(','),
        '--delay', NODEMON_CONFIG.delay.toString()
    ];

    const nodemon = spawn('npx', ['nodemon', ...nodemonArgs], {
        stdio: 'inherit',
        env: {
            ...process.env,
            ...NODEMON_CONFIG.env
        }
    });

    nodemon.on('close', (code) => {
        console.log(`\n🛑 Development server exited with code ${code}`);
        process.exit(code);
    });

    nodemon.on('error', (error) => {
        console.error('❌ Error starting development server:', error);
        process.exit(1);
    });

    // Handle graceful shutdown
    process.on('SIGINT', () => {
        console.log('\n🛑 Shutting down development server...');
        nodemon.kill('SIGINT');
    });

    process.on('SIGTERM', () => {
        console.log('\n🛑 Shutting down development server...');
        nodemon.kill('SIGTERM');
    });
}

if (require.main === module) {
    startDevelopmentServer();
}

module.exports = { startDevelopmentServer };