"""
Surveillance silencieuse des trades et patterns
Affiche un résumé toutes les 30s
"""
import json
import time
import requests
from datetime import datetime
from collections import defaultdict

API_URL = "http://localhost:8889/api/ai-surveillance"
INTERVAL = 30  # secondes

def get_positions():
    """Lit positions.json"""
    try:
        with open('positions.json', 'r') as f:
            data = json.load(f)
            return {k: v for k, v in data.items() if v}
    except:
        return {}

def get_api_data():
    """Récupère données API"""
    try:
        r = requests.get(API_URL, timeout=5)
        return r.json()
    except:
        return None

def parse_recent_logs(lines=200):
    """Parse les logs récents pour trades et blocages"""
    trades = []
    blocks = []
    pullback_blocks = []
    
    try:
        with open('trading_bot.log', 'r', encoding='utf-8') as f:
            recent = f.readlines()[-lines:]
        
        for line in recent:
            # Nouveaux trades
            if 'POSITION OUVERTE:' in line:
                parts = line.split('POSITION OUVERTE:')
                if len(parts) > 1:
                    symbol = parts[1].strip()
                    timestamp = line[:8]  # HH:MM:SS
                    trades.append((timestamp, symbol))
            
            # Blocages BB_position
            elif 'BB_position=' in line and 'BLOQUÉ' in line:
                if 'Symbol' in line:
                    parts = line.split()
                    for i, p in enumerate(parts):
                        if p.endswith('USDT:'):
                            symbol = p.replace(':', '')
                            bb = None
                            for j in range(i, min(i+10, len(parts))):
                                if 'BB_position=' in parts[j]:
                                    bb = parts[j].split('=')[1].split()[0]
                                    break
                            if bb:
                                blocks.append((symbol, float(bb), 'BB_high'))
            
            # Blocages PULLBACK spécifiques
            elif 'PULLBACK en zone haute BLOQUÉ' in line:
                parts = line.split()
                for i, p in enumerate(parts):
                    if p.endswith('USDT:'):
                        symbol = p.replace(':', '')
                        bb = rsi = None
                        for j in range(i, min(i+15, len(parts))):
                            if 'BB=' in parts[j]:
                                bb = parts[j].split('=')[1]
                            if 'RSI=' in parts[j]:
                                rsi = parts[j].split('=')[1]
                        pullback_blocks.append((symbol, bb, rsi))
    except:
        pass
    
    return trades, blocks, pullback_blocks

def main():
    print("\n" + "="*60)
    print("🔍 SURVEILLANCE SILENCIEUSE - Trades & Patterns")
    print("="*60)
    print("Rafraîchissement: 30s | Ctrl+C pour arrêter\n")
    
    last_trade_count = 0
    last_positions = set()
    
    while True:
        try:
            now = datetime.now().strftime("%H:%M:%S")
            
            # Positions actuelles
            positions = get_positions()
            pos_count = len(positions)
            current_symbols = set(positions.keys())
            
            # Nouveaux trades depuis dernière vérif
            new_trades = current_symbols - last_positions
            closed_trades = last_positions - current_symbols
            
            # Stats API
            api_data = get_api_data()
            ready_signals = 0
            patterns_ready = defaultdict(int)
            if api_data and 'data' in api_data:
                ready_signals = api_data['data'].get('ready_to_buy', 0)
                for sig in api_data['data'].get('ready_signals', []):
                    pattern = sig.get('pattern', 'UNKNOWN')
                    patterns_ready[pattern] += 1
            
            # Logs récents
            trades, blocks, pullback_blocks = parse_recent_logs(200)
            
            # Affichage
            print(f"\r[{now}] ", end="")
            print(f"Pos: {pos_count:2d} | Ready: {ready_signals:2d} | ", end="")
            
            if new_trades:
                print(f"🟢 NOUVEAUX: {', '.join(new_trades)} | ", end="")
            elif closed_trades:
                print(f"🔴 FERMÉS: {', '.join(closed_trades)} | ", end="")
            else:
                print("⚪ Stable | ", end="")
            
            # Patterns ready
            if patterns_ready:
                pattern_str = ' '.join([f"{p}:{c}" for p, c in patterns_ready.items()])
                print(f"[{pattern_str}]", end="")
            
            # Blocages récents (dernières 30s ~ 6 lignes de log)
            recent_blocks = blocks[-3:] if blocks else []
            recent_pullback = pullback_blocks[-2:] if pullback_blocks else []
            
            if recent_pullback:
                print(f" 🚫PB:{len(recent_pullback)}", end="")
            if recent_blocks:
                print(f" 🚫BB:{len(recent_blocks)}", end="")
            
            print("   ", end="", flush=True)
            
            # Résumé toutes les 5 minutes
            if int(time.time()) % 300 < 30:
                if trades or pullback_blocks:
                    print(f"\n\n📊 Résumé 5 dernières minutes:")
                    if trades:
                        print(f"   Trades: {len(trades)} ({', '.join([t[1] for t in trades[-5:]])})")
                    if pullback_blocks:
                        print(f"   PULLBACK bloqués (fin cycle): {len(pullback_blocks)}")
                        for sym, bb, rsi in pullback_blocks[-3:]:
                            print(f"      {sym}: BB={bb} RSI={rsi}")
                    print()
            
            last_positions = current_symbols
            time.sleep(INTERVAL)
            
        except KeyboardInterrupt:
            print("\n\n🛑 Surveillance arrêtée")
            break
        except Exception as e:
            print(f"\r⚠️ Erreur: {e}   ", end="", flush=True)
            time.sleep(INTERVAL)

if __name__ == "__main__":
    main()
