/**
 * CBD Universal Database - Phase 3 Working Startup
 * Simple and functional multi-paradigm database service
 */

import { CBDUniversalServiceSimple } from './server-phase3-working';

async function startService() {
    const service = new CBDUniversalServiceSimple(4180);

    // Graceful shutdown - only on explicit signals
    let shutdownInProgress = false;

    const gracefulShutdown = async (signal: string) => {
        if (shutdownInProgress) return;
        shutdownInProgress = true;

        console.log(`\n🛑 Received ${signal}. Shutting down CBD Universal Database Service...`);
        try {
            await service.stop();
            console.log('✅ Graceful shutdown completed');
            process.exit(0);
        } catch (error) {
            console.error('❌ Error during shutdown:', error);
            process.exit(1);
        }
    };

    // Only handle explicit shutdown signals
    process.on('SIGINT', () => gracefulShutdown('SIGINT'));
    process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));

    // Prevent process from exiting on unhandled promise rejections
    process.on('unhandledRejection', (reason) => {
        console.warn('⚠️ Unhandled Promise Rejection:', reason);
        // Don't exit, just log the warning
    });

    try {
        await service.start();
        console.log('✅ CBD Universal Database Service Phase 3 is ready!');
        console.log('');
        console.log('📋 Available endpoints:');
        console.log('  📊 Health: GET /health');
        console.log('  📈 Stats: GET /stats');
        console.log('  📄 Documents: POST|GET|PUT|DELETE /document/:collection[/:id]');
        console.log('  🔍 Vectors: POST /vector/store, POST /vector/search');
        console.log('  🕸️  Graph: POST /graph/node, POST /graph/relationship, GET /graph/node/:id');
        console.log('  🔑 Key-Value: POST /kv/set, GET /kv/:key, DELETE /kv/:key');
        console.log('  ⏰ Time-Series: POST /timeseries/write, POST /timeseries/query, GET /timeseries/measurements');
        console.log('');
        console.log('🎯 Press Ctrl+C to stop the service');
    } catch (error) {
        console.error('❌ Failed to start service:', error);
        process.exit(1);
    }
}

startService();
