#!/usr/bin/env node

/**
 * Next.js Warm-up Script
 * 
 * This script runs AFTER Next.js starts to warm up critical pages
 * and API routes by making actual HTTP requests to them.
 */

const http = require('http');

const criticalEndpoints = [
    '/automation-v2',
    '/api/automation/status',
    '/api/drift/balance',
    '/api/ai-learning-status',
    '/api/price-monitor'
];

async function makeRequest(path) {
    return new Promise((resolve) => {
        const options = {
            hostname: 'localhost',
            port: 3000,
            path: path,
            method: 'GET',
            timeout: 10000
        };

        const req = http.request(options, (res) => {
            console.log(`   ✅ Warmed: ${path} (${res.statusCode})`);
            resolve(true);
        });

        req.on('error', (err) => {
            console.log(`   ⚠️  Could not warm: ${path} - ${err.message}`);
            resolve(false);
        });

        req.on('timeout', () => {
            console.log(`   ⏰ Timeout warming: ${path}`);
            req.destroy();
            resolve(false);
        });

        req.end();
    });
}

async function warmUpNextJS() {
    console.log('🌡️ Warming up Next.js pages and API routes...');
    
    // Wait for Next.js to be ready
    console.log('⏳ Waiting for Next.js to be ready...');
    await new Promise(resolve => setTimeout(resolve, 3000));
    
    let warmed = 0;
    for (const endpoint of criticalEndpoints) {
        const success = await makeRequest(endpoint);
        if (success) warmed++;
        // Small delay between requests
        await new Promise(resolve => setTimeout(resolve, 500));
    }
    
    console.log(`🔥 Warm-up completed: ${warmed}/${criticalEndpoints.length} endpoints ready`);
}

// Only run if this script is executed directly
if (require.main === module) {
    warmUpNextJS().then(() => {
        console.log('✅ Next.js warm-up completed');
        process.exit(0);
    }).catch(error => {
        console.error('💥 Warm-up failed:', error);
        process.exit(1);
    });
}

module.exports = { warmUpNextJS };
