#!/usr/bin/env node
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createServeCommand = void 0;
/**
 * CLI command to start the management server for health checks and metrics
 */
const commander_1 = require("commander");
const module_system_1 = require("../module-system");
const config_1 = require("../config");
const structured_logger_1 = require("../module-system/structured-logger");
const path = __importStar(require("node:path"));
const fs = __importStar(require("node:fs"));
const logger = structured_logger_1.StructuredLoggerFactory.getLogger('serve-command');
function createServeCommand() {
    const cmd = new commander_1.Command('serve');
    cmd
        .description('Start the management server for health checks and metrics')
        .option('-p, --port <port>', 'Port to listen on', '8080')
        .option('-c, --config <file>', 'Path to configuration file')
        .option('--production', 'Enable production mode with all safety features')
        .option('--json', 'Use structured JSON logging')
        .action(async (options) => {
        try {
            // Load configuration
            const config = options.config
                ? JSON.parse(fs.readFileSync(path.resolve(options.config), 'utf8'))
                : (0, config_1.loadConfig)(process.cwd());
            const port = Number.parseInt(options.port, 10);
            const isProduction = options.production || process.env.NODE_ENV === 'production';
            // Configure structured logging if requested
            if (options.json) {
                structured_logger_1.StructuredLoggerFactory.configure({ format: 'json' });
            }
            logger.info('Starting management server', {
                port,
                production: isProduction,
                jsonLogging: options.json,
            });
            // Create module system with production features
            const moduleSystem = new module_system_1.ModuleSystem({
                resolution: {
                    baseUrl: process.cwd(),
                    ...config.moduleSystem?.resolution,
                },
                metrics: true,
                circuitBreakers: true,
                logger: true,
                managementServer: true,
                managementPort: port,
                resourceLimits: {
                    maxMemoryBytes: 1024 * 1024 * 1024, // 1GB
                    maxFileHandles: 1000,
                    maxCachedModules: 10000,
                    ...config.moduleSystem?.resourceLimits,
                },
            });
            // Start the management server
            const actualPort = await moduleSystem.startManagementServer(port);
            if (actualPort) {
                logger.info(`Management server started successfully`, {
                    port: actualPort,
                    endpoints: {
                        health: `http://localhost:${actualPort}/health`,
                        ready: `http://localhost:${actualPort}/health/ready`,
                        metrics: `http://localhost:${actualPort}/metrics`,
                        prometheus: `http://localhost:${actualPort}/metrics/prometheus`,
                    },
                });
                // Handle graceful shutdown
                const shutdown = async () => {
                    logger.info('Shutting down management server...');
                    await moduleSystem.shutdown();
                    process.exit(0);
                };
                process.on('SIGTERM', shutdown);
                process.on('SIGINT', shutdown);
                process.on('SIGHUP', shutdown);
                // Keep the process alive
                process.stdin.resume();
            }
            else {
                logger.error('Failed to start management server');
                process.exit(1);
            }
        }
        catch (error) {
            logger.error('Error starting management server', error);
            process.exit(1);
        }
    });
    return cmd;
}
exports.createServeCommand = createServeCommand;
//# sourceMappingURL=serve.js.map