#!/bin/bash
# Monitoring automatique de l'optimisation 14 jours
# Affiche progression toutes les 5 minutes

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

LOG_FILE="auto_monitor.log"

echo "🔄 Monitoring automatique démarré - $(date)" | tee -a $LOG_FILE
echo "Progression affichée toutes les 5 minutes" | tee -a $LOG_FILE
echo "" | tee -a $LOG_FILE

while true; do
    echo "════════════════════════════════════════════════════════════" | tee -a $LOG_FILE
    echo "📊 $(date '+%H:%M:%S') - PROGRESSION OPTIMISATION 14J" | tee -a $LOG_FILE
    echo "════════════════════════════════════════════════════════════" | tee -a $LOG_FILE

    # Check process
    if pgrep -f "optimize_bull_bear.py" > /dev/null; then
        PID=$(pgrep -f "optimize_bull_bear.py")
        ELAPSED=$(ps -p $PID -o etime --no-headers)
        echo "✅ Processus actif (PID $PID) - Temps écoulé: $ELAPSED" | tee -a $LOG_FILE

        # Check résultats
        if [ -f bull_bear_14d_results.json ]; then
            python3 << 'EOF' | tee -a $LOG_FILE
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'\nTests: {len(r)}/200 ({len(r)/2:.0f}%)')
print(f'Profitables: {len(profitable)} ({len(profitable)/len(r)*100:.1f}%)')

if len(r) > 0:
    # Estimation temps restant
    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 estimé: {hours}h {minutes}min')
        except:
            pass

if profitable:
    profitable.sort(key=lambda x: x['pnl_pct'], reverse=True)
    print(f'\n🏆 TOP 3:')
    for i, x in enumerate(profitable[:3], 1):
        print(f'{i}. PnL {x["pnl_pct"]:+.1f}% | PF {x["profit_factor"]:.2f} | Trades {x["trades"]} | {x["trades_by_strategy"]}')

    # Distribution stratégies
    all_strats = []
    for x in profitable:
        all_strats.extend(x['trades_by_strategy'].keys())
    counts = Counter(all_strats)
    print(f'\nStratégies:')
    for strat, count in counts.most_common():
        pct = count / sum(counts.values()) * 100
        print(f'  {strat}: {count} ({pct:.0f}%)')
EOF
        else
            echo "⏳ Pas de résultats encore..." | tee -a $LOG_FILE
        fi
    else
        echo "❌ Processus terminé ou arrêté" | tee -a $LOG_FILE

        # Check si terminé avec succès
        if [ -f bull_bear_14d_results.json ]; then
            TESTS=$(python3 -c "import json; r=json.load(open('bull_bear_14d_results.json')); print(len(r))")
            if [ "$TESTS" -ge 200 ]; then
                echo "" | tee -a $LOG_FILE
                echo "✅✅✅ OPTIMISATION TERMINÉE ! ✅✅✅" | tee -a $LOG_FILE
                echo "" | tee -a $LOG_FILE
                echo "Lancer l'analyse :" | tee -a $LOG_FILE
                echo "  python3 analyze_bull_bear_results.py" | tee -a $LOG_FILE
                exit 0
            fi
        fi
        break
    fi

    echo "" | tee -a $LOG_FILE

    # Attendre 5 minutes
    sleep 300
done

echo "Monitoring arrêté - $(date)" | tee -a $LOG_FILE
