#!/usr/bin/env python3
"""Vérification post-redémarrage avec nouveau système patterns"""

import json
import os
from datetime import datetime

print("\n" + "="*70)
print("🔍 VÉRIFICATION SYSTÈME APRÈS NETTOYAGE PATTERNS")
print("="*70)

# 1. État des processus
print("\n📊 ÉTAT DES SERVICES:")
print("-" * 70)

bot_pid_exists = os.path.exists("bot.pid")
print(f"   bot.pid: {'✅ Présent' if bot_pid_exists else '❌ Absent'}")

if bot_pid_exists:
    with open("bot.pid") as f:
        pid = f.read().strip()
        print(f"   PID Bot: {pid}")

# 2. Positions actuelles
print("\n📍 POSITIONS ACTUELLES:")
print("-" * 70)

try:
    with open('positions.json', 'r') as f:
        positions = json.load(f)
    
    if isinstance(positions, dict):
        print(f"\nTotal: {len(positions)} positions\n")
        
        patterns_count = {}
        for symbol, pos in positions.items():
            pattern = pos.get('pattern', 'UNKNOWN')
            entry = pos.get('entry_price', 0)
            
            # Compter les patterns
            patterns_count[pattern] = patterns_count.get(pattern, 0) + 1
            
            # Vérifier si pattern autorisé
            patterns_valides = ['CREUX_REBOUND', 'PULLBACK', 'TREND_CONTINUATION', 
                               'SQUEEZE_BREAKOUT', 'POSSIBLE_BLOCKED']
            status = "✅" if pattern in patterns_valides else "⚠️"
            
            print(f"   {status} {symbol}: {pattern} @ {entry}")
        
        print(f"\n📊 RÉPARTITION PAR PATTERN:")
        print("-" * 70)
        for pattern, count in sorted(patterns_count.items(), key=lambda x: x[1], reverse=True):
            pct = (count / len(positions) * 100) if len(positions) > 0 else 0
            print(f"   {pattern}: {count} ({pct:.1f}%)")
    
except Exception as e:
    print(f"   ❌ Erreur: {e}")

# 3. Logs récents
print("\n📝 LOGS RÉCENTS (patterns):")
print("-" * 70)

try:
    with open('trading_bot.log', 'r', encoding='utf-8') as f:
        lines = f.readlines()
    
    # Chercher les lignes avec Pattern/Score
    pattern_lines = [l.strip() for l in lines[-50:] if 'Pattern=' in l or 'pattern' in l.lower()]
    
    if pattern_lines:
        for line in pattern_lines[-10:]:
            print(f"   {line[:120]}")
    else:
        print("   Aucun log de pattern récent trouvé")
        print("   (Bot vient de démarrer - logs en cours de génération)")
    
except Exception as e:
    print(f"   ❌ Erreur lecture logs: {e}")

# 4. Erreurs récentes
print("\n⚠️ ERREURS RÉCENTES:")
print("-" * 70)

try:
    with open('trading_bot.log', 'r', encoding='utf-8') as f:
        lines = f.readlines()
    
    error_lines = [l.strip() for l in lines[-100:] if 'ERROR' in l or 'Exception' in l or 'Traceback' in l]
    
    if error_lines:
        print(f"   ⚠️ {len(error_lines)} erreur(s) détectée(s):")
        for line in error_lines[-5:]:
            print(f"   {line[:120]}")
    else:
        print("   ✅ Aucune erreur détectée")
    
except Exception as e:
    print(f"   ❌ Erreur: {e}")

# 5. Balance
print("\n💰 BALANCE:")
print("-" * 70)

try:
    # Lire depuis bot_settings.json si disponible
    if os.path.exists('bot_settings.json'):
        with open('bot_settings.json', 'r') as f:
            settings = json.load(f)
            balance = settings.get('balance_usdt', 0)
            print(f"   USDT: {balance:.2f}")
except:
    print("   Balance non disponible")

print("\n" + "="*70)
print("✅ VÉRIFICATION TERMINÉE")
print("="*70)
