#!/bin/bash
# Monitoring en temps réel avec rafraîchissement

cd /var/www/html/HyperOracle/crypto_trader/apollo_degen_bot

while true; do
    clear
    echo "════════════════════════════════════════════════════════════"
    echo "📊 OPTIMISATION 14 JOURS - $(date '+%H:%M:%S')"
    echo "════════════════════════════════════════════════════════════"
    echo ""

    # Check process
    if pgrep -f "optimize_bull_bear.py" > /dev/null; then
        PID=$(pgrep -f "optimize_bull_bear.py")
        CPU=$(ps -p $PID -o %cpu --no-headers | xargs)
        MEM=$(ps -p $PID -o %mem --no-headers | xargs)
        ELAPSED=$(ps -p $PID -o etime --no-headers | xargs)
        echo "✅ Processus actif"
        echo "   PID: $PID | CPU: ${CPU}% | MEM: ${MEM}% | Temps: $ELAPSED"
    else
        echo "❌ Processus non actif"
    fi
    echo ""

    # Résultats
    if [ -f bull_bear_14d_results.json ]; then
        python3 << 'PYEOF'
import json
from collections import Counter
from datetime import datetime

r = json.load(open('bull_bear_14d_results.json'))
profitable = [x for x in r if x['pnl_pct'] > 0 and x['profit_factor'] > 1.0]

print(f'Tests: {len(r)}/200 ({len(r)/2:.0f}%)')
print(f'Profitables: {len(profitable)} ({len(profitable)/len(r)*100:.1f}%)')

# Barre de progression
pct = len(r) / 200
bar_length = 50
filled = int(bar_length * pct)
bar = '█' * filled + '░' * (bar_length - filled)
print(f'\n[{bar}] {pct*100:.1f}%')

# Estimation temps
if len(r) >= 2:
    try:
        times = [datetime.fromisoformat(x['timestamp']) for x in r if 'timestamp' in x]
        if len(times) >= 2:
            elapsed = (max(times) - min(times)).total_seconds()
            sec_per_test = elapsed / len(r)
            remaining = (200 - len(r)) * sec_per_test
            hours = int(remaining / 3600)
            minutes = int((remaining % 3600) / 60)
            print(f'⏱️  Temps restant: ~{hours}h {minutes}min')
    except:
        pass

print()

if profitable:
    profitable.sort(key=lambda x: x['pnl_pct'], reverse=True)
    print('🏆 TOP 5 ACTUELS:')
    for i, x in enumerate(profitable[:5], 1):
        pnl_str = f"{x['pnl_pct']:+.1f}%"
        pf_str = f"{x['profit_factor']:.2f}" if x['profit_factor'] != float('inf') else "inf"
        print(f'{i}. PnL {pnl_str:>8} | PF {pf_str:>6} | Trades {x["trades"]:>2} | {x["trades_by_strategy"]}')

    print()

    # Distribution stratégies
    all_strats = []
    for x in profitable:
        all_strats.extend(x['trades_by_strategy'].keys())
    counts = Counter(all_strats)

    print('📈 Distribution stratégies:')
    total = sum(counts.values())
    for strat, count in counts.most_common():
        pct = count / total * 100
        bar_len = int(pct / 5)
        bar = '▓' * bar_len
        print(f'  {strat:>5}: {bar} {count} ({pct:.0f}%)')
else:
    print('⚠️  Aucune config profitable pour le moment')

PYEOF
    else
        echo "⏳ Pas de résultats encore..."
    fi

    echo ""
    echo "════════════════════════════════════════════════════════════"
    echo "Rafraîchissement dans 10 secondes... (Ctrl+C pour arrêter)"

    sleep 10
done
