#!/usr/bin/env node

const { execSync } = require('child_process');
const fs = require('fs');
const path = require('path');

const E2E_DIR = path.join(__dirname, 'e2e');
const RESULTS_FILE = path.join(__dirname, 'e2e-performance-results.json');

function measureE2ETestPerformance() {
    console.log('🚀 开始E2E性能测试...\n');
    
    const startTime = Date.now();
    
    try {
        const output = execSync('npm run test:e2e', {
            cwd: __dirname,
            encoding: 'utf8',
            stdio: 'pipe'
        });
        
        const endTime = Date.now();
        const duration = (endTime - startTime) / 1000;
        
        const results = {
            timestamp: new Date().toISOString(),
            duration: duration,
            durationFormatted: formatDuration(duration),
            success: true,
            message: 'E2E测试执行成功'
        };
        
        saveResults(results);
        
        console.log('\n✅ E2E测试执行成功！');
        console.log(`⏱️  总耗时: ${results.durationFormatted}`);
        console.log(`📊 性能评估: ${evaluatePerformance(duration)}`);
        
        return results;
    } catch (error) {
        const endTime = Date.now();
        const duration = (endTime - startTime) / 1000;
        
        const results = {
            timestamp: new Date().toISOString(),
            duration: duration,
            durationFormatted: formatDuration(duration),
            success: false,
            message: error.message || 'E2E测试执行失败'
        };
        
        saveResults(results);
        
        console.log('\n❌ E2E测试执行失败！');
        console.log(`⏱️  总耗时: ${results.durationFormatted}`);
        console.log(`📊 性能评估: ${evaluatePerformance(duration)}`);
        console.log(`💥 错误信息: ${error.message}`);
        
        return results;
    }
}

function formatDuration(seconds) {
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = Math.floor(seconds % 60);
    return `${minutes}分${remainingSeconds}秒`;
}

function evaluatePerformance(duration) {
    if (duration < 60) {
        return '🟢 优秀 - 执行时间在1分钟以内';
    } else if (duration < 90) {
        return '🟡 良好 - 执行时间在1.5分钟以内';
    } else if (duration < 120) {
        return '🟠 一般 - 执行时间在2分钟以内';
    } else {
        return '🔴 需要优化 - 执行时间超过2分钟';
    }
}

function saveResults(results) {
    const history = [];
    
    if (fs.existsSync(RESULTS_FILE)) {
        const data = fs.readFileSync(RESULTS_FILE, 'utf8');
        try {
            history.push(...JSON.parse(data));
        } catch (e) {
            console.warn('⚠️  无法解析历史结果文件');
        }
    }
    
    history.push(results);
    
    if (history.length > 10) {
        history.shift();
    }
    
    fs.writeFileSync(RESULTS_FILE, JSON.stringify(history, null, 2));
    
    console.log('\n📈 性能趋势分析:');
    analyzePerformanceTrend(history);
}

function analyzePerformanceTrend(history) {
    if (history.length < 2) {
        console.log('   需要更多测试数据来分析趋势');
        return;
    }
    
    const successfulTests = history.filter(r => r.success);
    if (successfulTests.length < 2) {
        console.log('   需要更多成功的测试数据来分析趋势');
        return;
    }
    
    const durations = successfulTests.map(r => r.duration);
    const avgDuration = durations.reduce((a, b) => a + b, 0) / durations.length;
    const minDuration = Math.min(...durations);
    const maxDuration = Math.max(...durations);
    
    console.log(`   平均执行时间: ${formatDuration(avgDuration)}`);
    console.log(`   最快执行时间: ${formatDuration(minDuration)}`);
    console.log(`   最慢执行时间: ${formatDuration(maxDuration)}`);
    
    const recentTests = successfulTests.slice(-3);
    if (recentTests.length >= 2) {
        const recentAvg = recentTests.reduce((a, b) => a + b.duration, 0) / recentTests.length;
        const olderTests = successfulTests.slice(0, -3);
        if (olderTests.length > 0) {
            const olderAvg = olderTests.reduce((a, b) => a + b.duration, 0) / olderTests.length;
            const improvement = ((olderAvg - recentAvg) / olderAvg * 100).toFixed(1);
            if (improvement > 0) {
                console.log(`   📉 性能提升: ${improvement}%`);
            } else {
                console.log(`   📈 性能下降: ${Math.abs(improvement)}%`);
            }
        }
    }
}

if (require.main === module) {
    measureE2ETestPerformance();
}

module.exports = { measureE2ETestPerformance };
