#!/usr/bin/env python3
"""Analyse les patterns utilisés dans les trades et positions"""

import json
from collections import Counter
from datetime import datetime, timedelta

print("\n" + "="*70)
print("📊 ANALYSE DES PATTERNS UTILISÉS")
print("="*70)

# Patterns attendus selon notre étude
PATTERNS_ATTENDUS = [
    'CREUX_REBOUND',
    'PULLBACK', 
    'TREND_CONTINUATION',
    'SQUEEZE_BREAKOUT',
    'HIGH_SCORE_OVERRIDE',
    'POSSIBLE_BLOCKED'
]

# 1. Analyser les positions actuelles
print("\n🔍 PATTERNS DES POSITIONS ACTUELLES:")
print("-" * 70)

try:
    with open('positions.json', 'r') as f:
        positions = json.load(f)
    
    if isinstance(positions, dict):
        patterns_pos = [p.get('pattern', 'UNKNOWN') for p in positions.values()]
    else:
        patterns_pos = [p.get('pattern', 'UNKNOWN') for p in positions]
    
    counter_pos = Counter(patterns_pos)
    total_pos = len(patterns_pos)
    
    for pattern, count in counter_pos.most_common():
        pct = (count / total_pos * 100) if total_pos > 0 else 0
        status = "✅" if pattern in PATTERNS_ATTENDUS else "⚠️"
        print(f"   {status} {pattern}: {count} ({pct:.1f}%)")
    
    print(f"\n   TOTAL: {total_pos} positions")
    
    # Identifier les patterns non attendus
    patterns_inattendus = [p for p in counter_pos.keys() if p not in PATTERNS_ATTENDUS]
    if patterns_inattendus:
        print(f"\n   ⚠️ PATTERNS NON ATTENDUS: {', '.join(patterns_inattendus)}")
    
except Exception as e:
    print(f"   ❌ Erreur lecture positions.json: {e}")

# 2. Analyser les trades récents (3 dernières heures)
print("\n📈 PATTERNS DES TRADES (3 dernières heures):")
print("-" * 70)

try:
    with open('trade_history.json', 'r') as f:
        history = json.load(f)
    
    # Filtrer les 3 dernières heures
    now = datetime.now()
    cutoff = now - timedelta(hours=3)
    
    recent_trades = []
    for trade in history:
        ts_str = trade.get('timestamp', '')
        if ts_str:
            # Gérer différents formats de timestamp
            ts_str = ts_str.replace('Z', '').replace('+00:00', '')
            try:
                ts = datetime.fromisoformat(ts_str)
                if ts > cutoff:
                    recent_trades.append(trade)
            except:
                pass
    
    if recent_trades:
        patterns_trades = [t.get('pattern', 'UNKNOWN') for t in recent_trades]
        counter_trades = Counter(patterns_trades)
        total_trades = len(recent_trades)
        
        for pattern, count in counter_trades.most_common():
            pct = (count / total_trades * 100) if total_trades > 0 else 0
            status = "✅" if pattern in PATTERNS_ATTENDUS else "⚠️"
            print(f"   {status} {pattern}: {count} ({pct:.1f}%)")
        
        print(f"\n   TOTAL: {total_trades} trades")
        
        # Identifier les patterns non attendus
        patterns_inattendus_trades = [p for p in counter_trades.keys() if p not in PATTERNS_ATTENDUS]
        if patterns_inattendus_trades:
            print(f"\n   ⚠️ PATTERNS NON ATTENDUS: {', '.join(patterns_inattendus_trades)}")
    else:
        print("   Aucun trade récent trouvé")
        
except Exception as e:
    print(f"   ❌ Erreur lecture trade_history.json: {e}")

# 3. Détails des positions avec patterns non attendus
print("\n🔎 DÉTAILS DES POSITIONS AVEC PATTERNS NON ATTENDUS:")
print("-" * 70)

try:
    for symbol, pos in positions.items():
        pattern = pos.get('pattern', 'UNKNOWN')
        if pattern not in PATTERNS_ATTENDUS:
            entry = pos.get('entry_price', 0)
            timestamp = pos.get('timestamp', 'N/A')
            print(f"   {symbol}:")
            print(f"      Pattern: {pattern}")
            print(f"      Entry: {entry}")
            print(f"      Timestamp: {timestamp}")
except:
    pass

# 4. Résumé des patterns autorisés
print("\n📋 PATTERNS AUTORISÉS (selon notre étude):")
print("-" * 70)
for pattern in PATTERNS_ATTENDUS:
    print(f"   ✅ {pattern}")

print("\n" + "="*70)
