#!/usr/bin/env node

/**
 * Simple ZAI Bridge License Interface
 * Clean, minimal license validation interface
 */

import express from 'express';
import cors from 'cors';
import path from 'path';
import { fileURLToPath } from 'url';
import { spawn } from 'child_process';
import { platform } from 'os';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

class SimpleLicenseServer {
    constructor(port = 3001) {
        this.port = port;
        this.app = express();
        this.setupMiddleware();
        this.setupRoutes();
    }

    setupMiddleware() {
        this.app.use(cors());
        this.app.use(express.json());
        this.app.use(express.static(__dirname));
    }

    setupRoutes() {
        // Serve the simple license interface
        this.app.get('/', (req, res) => {
            res.sendFile(path.join(__dirname, 'simple-license.html'));
        });

        // Simple license validation endpoint
        this.app.post('/api/license/validate', (req, res) => {
            const { licenseKey } = req.body;
            
            if (!licenseKey) {
                return res.status(400).json({
                    success: false,
                    error: 'License key is required'
                });
            }

            // Demo validation logic
            if (licenseKey.startsWith('ZAI-TEST-') || licenseKey.startsWith('ZAI-DEMO-')) {
                const tier = this.getTierFromToken(licenseKey);
                res.json({
                    success: true,
                    license: {
                        licenseId: licenseKey.substring(0, 15) + '...',
                        tier: tier,
                        status: 'Active',
                        features: this.getFeaturesForTier(tier)
                    },
                    message: 'License validated successfully'
                });
            } else {
                res.status(400).json({
                    success: false,
                    error: 'Invalid license key format. Use ZAI-TEST-* for demo.'
                });
            }
        });

        // Health check
        this.app.get('/health', (req, res) => {
            res.json({ status: 'healthy', timestamp: new Date().toISOString() });
        });
    }

    getTierFromToken(token) {
        if (token.includes('ENTERPRISE')) return 'Enterprise';
        if (token.includes('BUSINESS')) return 'Business';
        if (token.includes('TEAM')) return 'Team';
        if (token.includes('PERSONAL')) return 'Personal';
        return 'Demo';
    }

    getFeaturesForTier(tier) {
        const features = {
            'Personal': ['ai_to_ai_communication', 'basic_support'],
            'Team': ['ai_to_ai_communication', 'team_collaboration', 'priority_support'],
            'Business': ['ai_to_ai_communication', 'team_collaboration', 'advanced_analytics', 'priority_support'],
            'Enterprise': ['ai_to_ai_communication', 'team_collaboration', 'advanced_analytics', 'custom_integrations', 'dedicated_support'],
            'Demo': ['ai_to_ai_communication']
        };
        return features[tier] || features['Demo'];
    }

    async start() {
        return new Promise((resolve, reject) => {
            this.server = this.app.listen(this.port, (error) => {
                if (error) {
                    reject(error);
                } else {
                    console.log('🎨 Simple ZAI Bridge License Interface');
                    console.log('=====================================');
                    console.log(`🌐 Running at: http://localhost:${this.port}`);
                    console.log('🔑 Enter a license key to validate');
                    console.log('');
                    console.log('📝 Demo License Keys:');
                    console.log('  • ZAI-TEST-PERSONAL');
                    console.log('  • ZAI-TEST-TEAM');
                    console.log('  • ZAI-TEST-BUSINESS');
                    console.log('  • ZAI-TEST-ENTERPRISE');
                    console.log('');
                    
                    // Open browser
                    this.openBrowser(`http://localhost:${this.port}`);
                    
                    resolve();
                }
            });
        });
    }

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

    async stop() {
        if (this.server) {
            await new Promise((resolve) => {
                this.server.close(resolve);
            });
            console.log('🛑 Server stopped');
        }
    }
}

// Start the simple server
const server = new SimpleLicenseServer();

server.start().catch(error => {
    console.error('❌ Failed to start server:', error);
    process.exit(1);
});

// Graceful shutdown
process.on('SIGINT', async () => {
    console.log('\n🛑 Shutting down...');
    await server.stop();
    process.exit(0);
});

export { SimpleLicenseServer };
