#!/usr/bin/env python3
"""Test rapide pour vérifier pourquoi le bot n'achète pas"""

import os
import sys
import json
import time

os.chdir(os.path.dirname(os.path.abspath(__file__)))

# Charger les positions
positions = {}
if os.path.exists('positions.json'):
    with open('positions.json', 'r') as f:
        positions = json.load(f)

# Charger le cache de surveillance
cache = {}
if os.path.exists('ia_surveillance_cache.json'):
    with open('ia_surveillance_cache.json', 'r') as f:
        cache = json.load(f)

# Charger les settings
settings = {}
if os.path.exists('bot_settings.json'):
    with open('bot_settings.json', 'r') as f:
        settings = json.load(f)

print("=" * 60)
print("🔍 DIAGNOSTIC: POURQUOI LE BOT N'ACHÈTE PAS")
print("=" * 60)

# 1. Vérifier les positions
print(f"\n1️⃣ POSITIONS ACTUELLES: {len(positions)}")
for sym, pos in positions.items():
    print(f"   • {sym}: entry={pos.get('entry_price')} pattern={pos.get('pattern')}")

# 2. Vérifier les signaux prêts
ready_to_buy = cache.get('ready_to_buy', 0)
top_opps = cache.get('top_opportunities', [])
ready_signals = [o for o in top_opps if o.get('status') == 'ready']
print(f"\n2️⃣ SIGNAUX PRÊTS: {len(ready_signals)} (cache dit: {ready_to_buy})")
for sig in ready_signals[:5]:
    print(f"   • {sig['symbol']}: score={sig.get('score', 0)} pattern={sig.get('pattern', '?')}")

# 3. Vérifier max_positions
max_pos = settings.get('maxPositions', 10)
print(f"\n3️⃣ MAX POSITIONS: {max_pos} (actuel: {len(positions)})")
if len(positions) >= max_pos:
    print("   ❌ MAX POSITIONS ATTEINT - Aucun achat possible!")
else:
    print(f"   ✅ Peut encore ouvrir {max_pos - len(positions)} positions")

# 4. Vérifier auto_trade
auto_trade = settings.get('autoTrade', False)
print(f"\n4️⃣ AUTO TRADE: {auto_trade}")
if not auto_trade:
    print("   ❌ AUTO TRADE DÉSACTIVÉ - Aucun achat automatique!")

# 5. Vérifier les fichiers de pause
print("\n5️⃣ FICHIERS DE BLOCAGE:")
pause_files = ['.trading_pause']
for f in pause_files:
    if os.path.exists(f):
        print(f"   ❌ TROUVÉ: {f}")
    else:
        print(f"   ✅ Non trouvé: {f}")

# 6. Vérifier le market regime
print("\n6️⃣ MARKET REGIME:")
try:
    from market_regime import MarketRegimeDetector
    detector = MarketRegimeDetector()
    regime, details = detector.detect_regime()
    max_pos_regime = detector.get_max_positions()
    print(f"   Régime: {regime}")
    print(f"   Max positions (régime): {max_pos_regime}")
except Exception as e:
    print(f"   ⚠️ Erreur: {e}")

# 7. Vérifier logs du trading_bot
print("\n7️⃣ ANALYSE TRADING_BOT.LOG:")
try:
    with open('trading_bot.log', 'r', encoding='utf-8', errors='ignore') as f:
        lines = f.readlines()[-500:]
    
    # Chercher les dernières occurrences importantes
    pause_count = sum(1 for l in lines if 'PAUSE' in l or 'pause' in l)
    blocked_count = sum(1 for l in lines if 'BLOQUÉ' in l or 'bloqué' in l)
    safety_count = sum(1 for l in lines if 'Market safety' in l)
    
    print(f"   Mentions PAUSE: {pause_count}")
    print(f"   Mentions BLOQUÉ: {blocked_count}")
    print(f"   Mentions Market safety: {safety_count}")
    
    # Chercher le dernier message de safety
    for line in reversed(lines):
        if 'Market safety' in line:
            print(f"   Dernier safety: {line.strip()[:80]}")
            break
except Exception as e:
    print(f"   ⚠️ Erreur: {e}")

# 8. Vérifier si le bot tourne
print("\n8️⃣ BOT STATUS:")
if os.path.exists('bot.pid'):
    with open('bot.pid', 'r') as f:
        pid = f.read().strip()
    print(f"   PID dans bot.pid: {pid}")
    
    # Vérifier si le process tourne
    import subprocess
    result = subprocess.run(['tasklist', '/FI', f'PID eq {pid}'], capture_output=True, text=True)
    if 'python' in result.stdout.lower():
        print("   ✅ Process Python actif")
    else:
        print("   ❌ Process introuvable!")
else:
    print("   ❌ bot.pid n'existe pas")

print("\n" + "=" * 60)
print("🔍 FIN DIAGNOSTIC")
print("=" * 60)
