"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.StartCommand = void 0;
const child_process_1 = require("child_process");
const chalk_1 = __importDefault(require("chalk"));
const ora_1 = __importDefault(require("ora"));
const open_1 = __importDefault(require("open"));
const serverManager_1 = require("../managers/serverManager");
const processManager_1 = require("../utils/processManager");
const configManager_1 = require("../config/configManager");
class StartCommand {
    serverManager;
    processManager;
    configManager;
    constructor() {
        this.configManager = new configManager_1.ConfigManager();
        this.serverManager = new serverManager_1.ServerManager(this.configManager);
        this.processManager = new processManager_1.ProcessManager();
    }
    async execute(options) {
        const serverPort = parseInt(options.port || '3001');
        const webPort = parseInt(options.webPort || '5173');
        const serverOnly = options.serverOnly || false;
        console.log(chalk_1.default.blue('🚀 Starting One Logger...'));
        // Check if services are already running
        const serverRunning = await this.processManager.isPortInUse(serverPort);
        const webRunning = !serverOnly && await this.processManager.isPortInUse(webPort);
        if (serverRunning) {
            console.log(chalk_1.default.yellow(`⚠️  Server is already running on port ${serverPort}`));
        }
        if (webRunning) {
            console.log(chalk_1.default.yellow(`⚠️  Web UI is already running on port ${webPort}`));
        }
        if (serverRunning && (serverOnly || webRunning)) {
            console.log(chalk_1.default.green('✅ One Logger is already running'));
            if (!serverOnly) {
                console.log(chalk_1.default.cyan(`🌐 Web UI: http://localhost:${webPort}`));
            }
            console.log(chalk_1.default.cyan(`🔧 API Server: http://localhost:${serverPort}`));
            return;
        }
        try {
            // Start the server
            if (!serverRunning) {
                const serverSpinner = (0, ora_1.default)('Starting API server...').start();
                await this.serverManager.start(serverPort);
                serverSpinner.succeed(chalk_1.default.green(`✅ API server started on port ${serverPort}`));
            }
            // Start the web UI if not server-only mode
            if (!serverOnly && !webRunning) {
                const webSpinner = (0, ora_1.default)('Starting web UI...').start();
                await this.startWebUI(webPort);
                webSpinner.succeed(chalk_1.default.green(`✅ Web UI started on port ${webPort}`));
                // Open browser after a short delay
                setTimeout(async () => {
                    try {
                        await (0, open_1.default)(`http://localhost:${webPort}`);
                        console.log(chalk_1.default.cyan('🌐 Opened web UI in your default browser'));
                    }
                    catch (error) {
                        console.log(chalk_1.default.yellow('Could not open browser automatically'));
                    }
                }, 2000);
            }
            console.log(chalk_1.default.green('\n🎉 One Logger is now running!'));
            console.log(chalk_1.default.cyan(`🔧 API Server: http://localhost:${serverPort}`));
            if (!serverOnly) {
                console.log(chalk_1.default.cyan(`🌐 Web UI: http://localhost:${webPort}`));
            }
            console.log(chalk_1.default.gray('\nPress Ctrl+C to stop the services'));
            // Handle graceful shutdown
            this.setupGracefulShutdown();
        }
        catch (error) {
            console.error(chalk_1.default.red('❌ Failed to start One Logger:'), error);
            throw error;
        }
    }
    async startWebUI(port) {
        return new Promise((resolve, reject) => {
            const viteProcess = (0, child_process_1.spawn)('pnpm', ['run', 'dev', '--', '--port', port.toString()], {
                cwd: this.getViteAppPath(),
                stdio: 'pipe',
                env: {
                    ...process.env,
                    VITE_API_URL: `http://localhost:${this.configManager.getServerPort()}`
                }
            });
            let resolved = false;
            viteProcess.stdout?.on('data', (data) => {
                const output = data.toString();
                if (output.includes('Local:') && !resolved) {
                    resolved = true;
                    resolve();
                }
            });
            viteProcess.stderr?.on('data', (data) => {
                const error = data.toString();
                if (error.includes('EADDRINUSE') || error.includes('port') && error.includes('already')) {
                    if (!resolved) {
                        resolved = true;
                        reject(new Error(`Port ${port} is already in use`));
                    }
                }
            });
            viteProcess.on('error', (error) => {
                if (!resolved) {
                    resolved = true;
                    reject(error);
                }
            });
            // Store the process for cleanup
            this.processManager.addProcess('web-ui', viteProcess);
            // Timeout after 30 seconds
            setTimeout(() => {
                if (!resolved) {
                    resolved = true;
                    reject(new Error('Timeout starting web UI'));
                }
            }, 30000);
        });
    }
    getViteAppPath() {
        // Assuming the CLI app is in apps/cli-app and vite app is in apps/vite-web-server
        return require('path').resolve(__dirname, '../../../vite-web-server');
    }
    setupGracefulShutdown() {
        const shutdown = async () => {
            console.log(chalk_1.default.yellow('\n🛑 Shutting down One Logger...'));
            try {
                await this.serverManager.stop();
                await this.processManager.killAll();
                console.log(chalk_1.default.green('✅ One Logger stopped successfully'));
                process.exit(0);
            }
            catch (error) {
                console.error(chalk_1.default.red('❌ Error during shutdown:'), error);
                process.exit(1);
            }
        };
        process.on('SIGINT', shutdown);
        process.on('SIGTERM', shutdown);
    }
}
exports.StartCommand = StartCommand;
//# sourceMappingURL=start.js.map