#!/usr/bin/env node

/**
 * ZAI Bridge License GUI Startup Script
 * Starts the license management GUI server
 */

import { LicenseAPIServer } from './license-api-server.js';
import { spawn } from 'child_process';
import { platform } from 'os';

class LicenseGUIStarter {
    constructor() {
        this.server = null;
        this.browserProcess = null;
        this.port = process.env.ZAI_GUI_PORT || 8080;
    }

    async start() {
        try {
            console.log('🚀 Starting ZAI Bridge License GUI...');
            
            // Start the API server
            this.server = new LicenseAPIServer(this.port);
            await this.server.start();
            
            // Wait a moment for server to be ready
            await new Promise(resolve => setTimeout(resolve, 1000));
            
            // Open browser
            this.openBrowser();
            
            console.log('\n✅ ZAI Bridge License GUI is ready!');
            console.log('📋 You can now:');
            console.log('   • Enter your ZAI license key');
            console.log('   • View license status and usage');
            console.log('   • Manage connected devices');
            console.log('   • Monitor AI-to-AI operations');
            
        } catch (error) {
            console.error('❌ Failed to start License GUI:', error.message);
            process.exit(1);
        }
    }

    openBrowser() {
        const url = `http://localhost:${this.port}`;
        
        try {
            let command;
            let args;
            
            switch (platform()) {
                case 'darwin': // macOS
                    command = 'open';
                    args = [url];
                    break;
                case 'win32': // Windows
                    command = 'start';
                    args = ['', url];
                    break;
                default: // Linux and others
                    command = 'xdg-open';
                    args = [url];
                    break;
            }
            
            this.browserProcess = spawn(command, args, {
                detached: true,
                stdio: 'ignore'
            });
            
            this.browserProcess.unref();
            console.log(`🌐 Opening browser at ${url}`);
            
        } catch (error) {
            console.log(`🌐 Please open your browser and navigate to: ${url}`);
        }
    }

    async stop() {
        console.log('\n🛑 Shutting down License GUI...');
        
        if (this.browserProcess) {
            try {
                this.browserProcess.kill();
            } catch (error) {
                // Browser process may already be closed
            }
        }
        
        if (this.server) {
            await this.server.stop();
        }
        
        console.log('✅ License GUI stopped');
    }
}

// Handle command line arguments
const args = process.argv.slice(2);
const showHelp = args.includes('--help') || args.includes('-h');

if (showHelp) {
    console.log(`
🔐 ZAI Bridge License GUI

Usage: node start-license-gui.js [options]

Options:
  --help, -h     Show this help message
  --port PORT    Set the server port (default: 8080)
  --no-browser   Don't automatically open browser

Environment Variables:
  ZAI_GUI_PORT   Set the server port (default: 8080)

Examples:
  node start-license-gui.js
  node start-license-gui.js --port 3000
  ZAI_GUI_PORT=3000 node start-license-gui.js
`);
    process.exit(0);
}

// Parse port from command line
const portIndex = args.indexOf('--port');
if (portIndex !== -1 && args[portIndex + 1]) {
    process.env.ZAI_GUI_PORT = args[portIndex + 1];
}

// Start the GUI
const gui = new LicenseGUIStarter();

gui.start().catch(error => {
    console.error('❌ Startup failed:', error);
    process.exit(1);
});

// Graceful shutdown
process.on('SIGINT', async () => {
    await gui.stop();
    process.exit(0);
});

process.on('SIGTERM', async () => {
    await gui.stop();
    process.exit(0);
});

// Handle uncaught exceptions
process.on('uncaughtException', async (error) => {
    console.error('❌ Uncaught exception:', error);
    await gui.stop();
    process.exit(1);
});

process.on('unhandledRejection', async (reason, promise) => {
    console.error('❌ Unhandled rejection at:', promise, 'reason:', reason);
    await gui.stop();
    process.exit(1);
});

export { LicenseGUIStarter };
