import axios from 'axios';

async function finalVerify() {
    try {
        console.log("🔍 COMPREHENSIVE SYSTEM VERIFICATION 🔍");

        // 1. Check API Heartbeat
        const statusRes = await axios.get('http://localhost:5000/api/status');
        const state = statusRes.data;
        console.log(`✅ Backend API: Active (Uptime: ${(state.uptime / 60000).toFixed(2)} mins)`);

        // 2. Verify Symbols & Rule Engines
        const symbols = Object.keys(state.symbols);
        console.log(`✅ Monitored Symbols: ${symbols.join(', ')}`);

        symbols.forEach(s => {
            const sym = state.symbols[s];
            const rulesPassed = Object.values(sym.rules).filter((r: any) => r.passed).length;
            const rulesTotal = Object.keys(sym.rules).length;
            console.log(`   🔸 ${s}: Rules ${rulesPassed}/${rulesTotal} Passing | Last Signal: ${sym.signal}`);
        });

        // 3. Verify Profiles & Global Config
        console.log('\n--- 🛠 INFRASTRUCTURE CHECK ---');
        try {
            const configRes = await axios.get('http://localhost:5000/api/config');
            console.log(`✅ Config Engine: Providing synchronized parameters to all clusters.`);
            console.log(`   Master Symbols: ${configRes.data.SYMBOLS.join(', ')}`);
        } catch (e) {
            console.log("❌ Config Endpoint unreachable.");
        }

        // 4. Signal Alert Propagation
        console.log('\n--- 📡 SIGNAL PROPAGATION ---');
        if (state.alerts.length > 0) {
            const latestSignal = state.alerts.filter((a: any) => a.type === 'signal').pop();
            if (latestSignal) {
                console.log(`✅ Recent Signal Found: ${latestSignal.symbol} at ${new Date(latestSignal.timestamp).toLocaleTimeString()}`);
                console.log(`   Message snippet: ${latestSignal.message.substring(0, 50)}...`);
            } else {
                console.log("ℹ️ No recent 'BUY/SELL' signals detected in the current buffer.");
            }
        }

        console.log('\n--- 💰 ACTIVE AUTO-TRADING ---');
        if (state.positions.length > 0) {
            console.log(`🔥 ALERT: Active Auto-Trades detected!`);
            state.positions.forEach((p: any) => {
                console.log(`   📍 [${p.symbol}] ${p.side} | Profile: ${p.profileId || 'System'} | PnL: ${p.unrealizedPnlPercent?.toFixed(2)}%`);
            });
        } else {
            console.log("ℹ️ Engine IDLE: Waiting for 100% rule alignment for execution.");
        }

        console.log("\n🚀 VERIFICATION COMPLETE: System architecture is healthy and reactive.");

    } catch (err: any) {
        console.error('❌ CRITICAL: Failed to communicate with Bot Engine.', err.message);
    }
}

finalVerify();
