/**
 * ZAI Bridge License API Server
 * Provides REST API endpoints for the license manager GUI
 */

import express from 'express';
import cors from 'cors';
import path from 'path';
import { fileURLToPath } from 'url';
import { LicenseManager } from '../licensing/licenseManager.js';
import { MCPLicenseValidator } from '../licensing/mcpLicenseValidator.js';

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

class LicenseAPIServer {
    constructor(port = 8080) {
        this.port = port;
        this.app = express();
        this.licenseManager = new LicenseManager();
        this.licenseValidator = new MCPLicenseValidator();
        this.currentLicense = null;
        
        this.setupMiddleware();
        this.setupRoutes();
        this.initializeLicenseSystem();
    }

    setupMiddleware() {
        // Enable CORS for all routes
        this.app.use(cors({
            origin: ['http://localhost:3000', 'http://127.0.0.1:3000', 'file://'],
            credentials: true
        }));
        
        // Parse JSON bodies
        this.app.use(express.json());
        
        // Serve static files from the GUI directory
        this.app.use('/gui', express.static(__dirname));
        
        // Request logging
        this.app.use((req, res, next) => {
            console.log(`${new Date().toISOString()} - ${req.method} ${req.path}`);
            next();
        });
    }

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

        // API Routes
        this.app.get('/api/status', this.handleStatus.bind(this));
        this.app.post('/api/license/validate', this.handleLicenseValidation.bind(this));
        this.app.get('/api/license/status', this.handleLicenseStatus.bind(this));
        this.app.post('/api/license/clear', this.handleLicenseClear.bind(this));
        this.app.get('/api/license/devices', this.handleDeviceList.bind(this));
        this.app.delete('/api/license/devices/:deviceId', this.handleDeviceRemoval.bind(this));
        this.app.get('/api/license/usage', this.handleUsageStats.bind(this));
        this.app.post('/api/license/refresh', this.handleLicenseRefresh.bind(this));

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

        // Error handling middleware
        this.app.use(this.errorHandler.bind(this));
    }

    async initializeLicenseSystem() {
        try {
            console.log('🔐 Initializing license system for GUI...');
            await this.licenseManager.initialize();
            await this.licenseValidator.initialize();
            console.log('✅ License system initialized for GUI');
        } catch (error) {
            console.error('❌ Failed to initialize license system for GUI:', error.message);
        }
    }

    // API Route Handlers

    async handleStatus(req, res) {
        try {
            const status = {
                server: 'running',
                timestamp: new Date().toISOString(),
                license: this.currentLicense ? {
                    isValid: true,
                    tier: this.currentLicense.tier,
                    status: this.currentLicense.status
                } : {
                    isValid: false,
                    tier: null,
                    status: 'no_license'
                },
                bridge: {
                    connected: true,
                    version: '1.1.1'
                }
            };
            
            res.json({ success: true, status });
        } catch (error) {
            res.status(500).json({ 
                success: false, 
                error: 'Failed to get server status',
                details: error.message 
            });
        }
    }

    async handleLicenseValidation(req, res) {
        try {
            const { licenseKey } = req.body;
            
            if (!licenseKey) {
                return res.status(400).json({
                    success: false,
                    error: 'License key is required'
                });
            }

            console.log(`🔐 Validating license via GUI: ${licenseKey.substring(0, 10)}...`);
            
            // Validate the license using the license manager
            const validation = await this.licenseManager.validateLicense(licenseKey);
            
            if (validation.isValid) {
                this.currentLicense = validation.license;
                
                // Also validate through the MCP validator for consistency
                const mcpValidation = await this.licenseValidator.validateMCPStartup();
                
                res.json({
                    success: true,
                    license: {
                        ...validation.license,
                        deviceValidation: validation.deviceValidation,
                        mcpValidation: mcpValidation.canStart
                    },
                    message: 'License validated successfully'
                });
                
                console.log(`✅ License validated via GUI: ${validation.license.licenseId}`);
            } else {
                res.status(400).json({
                    success: false,
                    error: validation.error || 'License validation failed'
                });
                
                console.log(`❌ License validation failed via GUI: ${validation.error}`);
            }
        } catch (error) {
            console.error('❌ License validation error:', error);
            res.status(500).json({
                success: false,
                error: 'Internal server error during license validation',
                details: error.message
            });
        }
    }

    async handleLicenseStatus(req, res) {
        try {
            if (!this.currentLicense) {
                return res.json({
                    success: false,
                    error: 'No active license'
                });
            }

            // Get fresh license status
            const licenseStatus = this.licenseManager.getLicenseStatus();
            
            // Get device information
            const devices = this.currentLicense.devices || [];
            
            // Get usage statistics
            const usage = this.currentLicense.usage || {
                totalSessions: 0,
                totalConversations: 0,
                totalMessages: 0,
                lastUsed: null
            };

            res.json({
                success: true,
                license: {
                    ...this.currentLicense,
                    status: licenseStatus.status,
                    devices,
                    usage,
                    lastChecked: new Date().toISOString()
                }
            });
        } catch (error) {
            console.error('❌ Failed to get license status:', error);
            res.status(500).json({
                success: false,
                error: 'Failed to get license status',
                details: error.message
            });
        }
    }

    async handleLicenseClear(req, res) {
        try {
            this.currentLicense = null;
            
            res.json({
                success: true,
                message: 'License cleared successfully'
            });
            
            console.log('🗑️ License cleared via GUI');
        } catch (error) {
            console.error('❌ Failed to clear license:', error);
            res.status(500).json({
                success: false,
                error: 'Failed to clear license',
                details: error.message
            });
        }
    }

    async handleDeviceList(req, res) {
        try {
            if (!this.currentLicense) {
                return res.json({
                    success: false,
                    error: 'No active license'
                });
            }

            const devices = this.currentLicense.devices || [];
            
            res.json({
                success: true,
                devices: devices.map(device => ({
                    ...device,
                    isCurrentDevice: device.deviceId === this.licenseManager.deviceId
                }))
            });
        } catch (error) {
            console.error('❌ Failed to get device list:', error);
            res.status(500).json({
                success: false,
                error: 'Failed to get device list',
                details: error.message
            });
        }
    }

    async handleDeviceRemoval(req, res) {
        try {
            const { deviceId } = req.params;
            
            if (!this.currentLicense) {
                return res.status(400).json({
                    success: false,
                    error: 'No active license'
                });
            }

            // Remove device from license
            const removedDevice = await this.licenseManager.removeDeviceFromLicense(
                this.currentLicense.licenseId, 
                deviceId
            );
            
            // Update current license data
            const validation = await this.licenseManager.validateLicense();
            if (validation.isValid) {
                this.currentLicense = validation.license;
            }
            
            res.json({
                success: true,
                removedDevice,
                message: 'Device removed successfully'
            });
            
            console.log(`🗑️ Device removed via GUI: ${deviceId}`);
        } catch (error) {
            console.error('❌ Failed to remove device:', error);
            res.status(500).json({
                success: false,
                error: 'Failed to remove device',
                details: error.message
            });
        }
    }

    async handleUsageStats(req, res) {
        try {
            if (!this.currentLicense) {
                return res.json({
                    success: false,
                    error: 'No active license'
                });
            }

            const usage = this.currentLicense.usage || {};
            const devices = this.currentLicense.devices || [];
            const tierConfig = this.currentLicense.tierConfig || {};
            
            res.json({
                success: true,
                usage: {
                    ...usage,
                    devicesUsed: devices.length,
                    maxDevices: tierConfig.maxDevices || 1,
                    deviceUsagePercent: Math.round((devices.length / (tierConfig.maxDevices || 1)) * 100)
                }
            });
        } catch (error) {
            console.error('❌ Failed to get usage stats:', error);
            res.status(500).json({
                success: false,
                error: 'Failed to get usage statistics',
                details: error.message
            });
        }
    }

    async handleLicenseRefresh(req, res) {
        try {
            if (!this.currentLicense) {
                return res.json({
                    success: false,
                    error: 'No active license to refresh'
                });
            }

            // Re-validate the current license
            const validation = await this.licenseManager.validateLicense();
            
            if (validation.isValid) {
                this.currentLicense = validation.license;
                
                res.json({
                    success: true,
                    license: this.currentLicense,
                    message: 'License refreshed successfully'
                });
                
                console.log(`🔄 License refreshed via GUI: ${this.currentLicense.licenseId}`);
            } else {
                res.status(400).json({
                    success: false,
                    error: validation.error || 'License refresh failed'
                });
            }
        } catch (error) {
            console.error('❌ Failed to refresh license:', error);
            res.status(500).json({
                success: false,
                error: 'Failed to refresh license',
                details: error.message
            });
        }
    }

    errorHandler(error, req, res, next) {
        console.error('❌ API Error:', error);
        
        if (res.headersSent) {
            return next(error);
        }
        
        res.status(500).json({
            success: false,
            error: 'Internal server error',
            details: process.env.NODE_ENV === 'development' ? error.message : 'An error occurred'
        });
    }

    async start() {
        try {
            await new Promise((resolve, reject) => {
                this.server = this.app.listen(this.port, (error) => {
                    if (error) {
                        reject(error);
                    } else {
                        resolve();
                    }
                });
            });
            
            console.log(`🌐 ZAI Bridge License GUI running at:`);
            console.log(`   • Local:   http://localhost:${this.port}`);
            console.log(`   • Network: http://127.0.0.1:${this.port}`);
            console.log(`   • GUI:     http://localhost:${this.port}/`);
            console.log(`   • API:     http://localhost:${this.port}/api`);
            
            return true;
        } catch (error) {
            console.error('❌ Failed to start license GUI server:', error.message);
            throw error;
        }
    }

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

// Export for use in other modules
export { LicenseAPIServer };

// Start server if this file is run directly
if (import.meta.url === `file://${process.argv[1]}`) {
    const server = new LicenseAPIServer();
    
    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 license GUI server...');
        await server.stop();
        process.exit(0);
    });
}
