#!/usr/bin/env python3
"""
Génère un diagramme visuel de l'architecture du système IA
"""

import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from matplotlib.patches import FancyBboxPatch, FancyArrowPatch
import numpy as np

# Configuration
plt.rcParams['font.family'] = 'Arial'
plt.rcParams['font.size'] = 9

# Créer la figure
fig = plt.figure(figsize=(20, 14))
fig.suptitle('🤖 ARCHITECTURE DU SYSTÈME IA - CRYPTO TRADING BOT', 
             fontsize=20, fontweight='bold', y=0.98)

# Créer une grille pour organiser les sections
gs = fig.add_gridspec(4, 3, hspace=0.4, wspace=0.3, 
                      left=0.05, right=0.95, top=0.94, bottom=0.05)

# Couleurs
COLOR_MODULE = '#3498db'
COLOR_PATTERN = '#2ecc71'
COLOR_FILTER = '#e74c3c'
COLOR_SCORE = '#f39c12'
COLOR_DECISION = '#9b59b6'

# ==================== SECTION 1: MODULES D'ANALYSE ====================
ax1 = fig.add_subplot(gs[0:2, 0])
ax1.set_xlim(0, 10)
ax1.set_ylim(0, 14)
ax1.axis('off')
ax1.set_title('📊 14 MODULES D\'ANALYSE (GPU)', fontsize=14, fontweight='bold', pad=10)

modules = [
    ("AI Advanced Scorer", "Score GPU 0-100"),
    ("Performance Analyzer", "Whitelist/Blacklist"),
    ("Volatility Scorer", "Cycles réguliers"),
    ("Dynamic Blacklist", "Auto-blocage perdants"),
    ("Multi-Timeframe", "3 échelles temps"),
    ("Volume Profile", "Zones institutionnelles"),
    ("Market Regime", "BULL/NEUTRAL/BEAR"),
    ("Long-Term Trend", "4h-8h-12h"),
    ("Smart Rotation", "Optimise allocation"),
    ("Dynamic SL/TP", "Stop-Loss adaptatifs"),
    ("Time Pattern", "Patterns horaires"),
    ("Correlation", "Corrélation secteur"),
    ("Monte Carlo", "1000 simulations"),
    ("Ensemble", "4 modèles ML"),
]

y_pos = 13
for i, (name, desc) in enumerate(modules):
    # Boîte colorée
    box = FancyBboxPatch((0.5, y_pos - 0.8), 9, 0.7, 
                         boxstyle="round,pad=0.05", 
                         facecolor=COLOR_MODULE, 
                         edgecolor='navy', linewidth=1.5, alpha=0.7)
    ax1.add_patch(box)
    
    # Texte
    ax1.text(1, y_pos - 0.45, f"{i+1}. {name}", 
            fontsize=9, fontweight='bold', color='white', va='center')
    ax1.text(9.5, y_pos - 0.45, desc, 
            fontsize=7, color='white', va='center', ha='right', style='italic')
    
    y_pos -= 0.95

# ==================== SECTION 2: PATTERNS D'ACHAT ====================
ax2 = fig.add_subplot(gs[0:2, 1])
ax2.set_xlim(0, 10)
ax2.set_ylim(0, 14)
ax2.axis('off')
ax2.set_title('🎯 12 PATTERNS D\'ACHAT (Priorités)', fontsize=14, fontweight='bold', pad=10)

patterns = [
    ("STRONG_UPTREND", "+20pts", "Tendance forte persistante"),
    ("EARLY_BREAKOUT", "+25pts", "Début mouvement haussier"),
    ("CONSOLIDATION_BREAKOUT", "+22pts", "Sortie consolidation"),
    ("EMA_BULLISH", "+18pts", "EMA9 > EMA21 confirmé"),
    ("CROSSOVER_IMMINENT", "+10pts", "EMA proche croisement"),
    ("SQUEEZE_BREAKOUT", "+15pts", "BB serrées + breakout"),
    ("RSI_REVERSAL", "+20pts", "Rebond survente"),
    ("PULLBACK", "Variable", "Correction saine"),
    ("CREUX_EMA", "Variable", "EMA9 < EMA21 rebond"),
    ("BB_SQUEEZE", "Variable", "Compression BB"),
]

y_pos = 13
for i, (name, bonus, desc) in enumerate(patterns):
    # Boîte colorée avec gradient
    box = FancyBboxPatch((0.5, y_pos - 0.8), 9, 0.7, 
                         boxstyle="round,pad=0.05", 
                         facecolor=COLOR_PATTERN, 
                         edgecolor='darkgreen', linewidth=1.5, alpha=0.7)
    ax2.add_patch(box)
    
    # Texte
    ax2.text(1, y_pos - 0.45, f"#{i+1} {name}", 
            fontsize=9, fontweight='bold', color='white', va='center')
    ax2.text(6.5, y_pos - 0.45, bonus, 
            fontsize=8, color='yellow', va='center', fontweight='bold')
    ax2.text(9.5, y_pos - 0.45, desc, 
            fontsize=7, color='white', va='center', ha='right', style='italic')
    
    y_pos -= 1.3

# ==================== SECTION 3: FILTRES DE SÉCURITÉ ====================
ax3 = fig.add_subplot(gs[0:2, 2])
ax3.set_xlim(0, 10)
ax3.set_ylim(0, 14)
ax3.axis('off')
ax3.set_title('🛡️ 8 FILTRES DE SÉCURITÉ', fontsize=14, fontweight='bold', pad=10)

filters = [
    ("FIN DE CYCLE", "BB>0.90 + RSI>70", "Surachat extrême"),
    ("ACTIVE_CRASH", "Mom3<-3% OU Mom5<-4%", "Chute brutale"),
    ("STRONG_DOWNTREND", "EMA diff<-1%", "Tendance baissière"),
    ("RSI_TRAP", "RSI bas + Mom négatif", "Piège continuation"),
    ("PATTERN HOLD", "Signal maintenance", "Pas d'entrée"),
    ("EMA DIFF NÉGATIF", "EMA9 < EMA21", "Tendance baissière CT"),
    ("BB POSITION < 0.20", "Zone trop basse", "Falling knife"),
    ("DEAD CAT BOUNCE", "Tendance 4h-8h ↓", "Rebond piégé"),
]

y_pos = 13
for i, (name, condition, desc) in enumerate(filters):
    # Boîte rouge
    box = FancyBboxPatch((0.5, y_pos - 0.8), 9, 0.7, 
                         boxstyle="round,pad=0.05", 
                         facecolor=COLOR_FILTER, 
                         edgecolor='darkred', linewidth=2, alpha=0.75)
    ax3.add_patch(box)
    
    # Icône warning
    ax3.text(0.8, y_pos - 0.45, '⚠️', fontsize=10, va='center')
    
    # Texte
    ax3.text(1.5, y_pos - 0.45, name, 
            fontsize=9, fontweight='bold', color='white', va='center')
    ax3.text(9.5, y_pos - 0.45, f"{condition}\n{desc}", 
            fontsize=6.5, color='white', va='center', ha='right')
    
    y_pos -= 1.65

# ==================== SECTION 4: FLUX DE DÉCISION ====================
ax4 = fig.add_subplot(gs[2, :])
ax4.set_xlim(0, 100)
ax4.set_ylim(0, 12)
ax4.axis('off')
ax4.set_title('🔄 FLUX DE DÉCISION (Cycle: 5 secondes)', fontsize=14, fontweight='bold', pad=10)

# Étapes du flux
steps = [
    (10, 6, "1. RÉCUPÉRATION\nDonnées", COLOR_MODULE),
    (25, 6, "2. EXTRACTION\n50+ Features", COLOR_MODULE),
    (40, 6, "3. ANALYSE\n14 Modules", COLOR_MODULE),
    (55, 6, "4. SCORING\n0-100 points", COLOR_SCORE),
    (70, 6, "5. PATTERN\n12 Stratégies", COLOR_PATTERN),
    (85, 6, "6. FILTRES\n8 Sécurités", COLOR_FILTER),
]

for i, (x, y, text, color) in enumerate(steps):
    # Boîte étape
    box = FancyBboxPatch((x-5, y-2), 10, 4, 
                         boxstyle="round,pad=0.2", 
                         facecolor=color, 
                         edgecolor='black', linewidth=2, alpha=0.8)
    ax4.add_patch(box)
    
    # Texte
    ax4.text(x, y, text, fontsize=10, fontweight='bold', 
            color='white', ha='center', va='center')
    
    # Flèche vers étape suivante
    if i < len(steps) - 1:
        arrow = FancyArrowPatch((x+5.5, y), (steps[i+1][0]-5.5, y),
                               arrowstyle='->', mutation_scale=30, 
                               linewidth=3, color='black')
        ax4.add_patch(arrow)

# Décision finale
decision_box = FancyBboxPatch((40, 1), 20, 3, 
                             boxstyle="round,pad=0.2", 
                             facecolor=COLOR_DECISION, 
                             edgecolor='black', linewidth=3, alpha=0.9)
ax4.add_patch(decision_box)
ax4.text(50, 2.5, "DÉCISION FINALE", fontsize=12, fontweight='bold', 
        color='white', ha='center', va='center')

# Flèches vers décisions
arrow1 = FancyArrowPatch((85, 4), (60, 2.5),
                        arrowstyle='->', mutation_scale=25, 
                        linewidth=2.5, color='green', linestyle='--')
ax4.add_patch(arrow1)
ax4.text(73, 3.5, "Score ≥ 75", fontsize=9, color='green', fontweight='bold')

# Résultats
ax4.text(30, 0.3, "❌ WATCHING", fontsize=10, color='orange', fontweight='bold')
ax4.text(50, 0.3, "✅ READY TO BUY", fontsize=10, color='green', fontweight='bold')
ax4.text(72, 0.3, "🚫 BLOCKED", fontsize=10, color='red', fontweight='bold')

# ==================== SECTION 5: SYSTÈME DE SCORING ====================
ax5 = fig.add_subplot(gs[3, :])
ax5.set_xlim(0, 100)
ax5.set_ylim(0, 10)
ax5.axis('off')
ax5.set_title('💯 SYSTÈME DE SCORING (0-100 points)', fontsize=14, fontweight='bold', pad=10)

# Score de base
base_box = FancyBboxPatch((5, 6), 15, 3, 
                         boxstyle="round,pad=0.1", 
                         facecolor='#34495e', 
                         edgecolor='black', linewidth=2, alpha=0.8)
ax5.add_patch(base_box)
ax5.text(12.5, 7.5, "SCORE DE BASE\nGPU Scorer", fontsize=10, fontweight='bold', 
        color='white', ha='center', va='center')

# Bonus
bonus_items = [
    (25, "TOP 20", "+15"),
    (35, "Whitelist Perf", "+15"),
    (45, "Vol. Excellente", "+20"),
    (55, "Pattern Fort", "+25"),
    (65, "Corrél. Secteur", "+15"),
]

for x, name, bonus in bonus_items:
    box = FancyBboxPatch((x-3, 6), 6, 3, 
                         boxstyle="round,pad=0.1", 
                         facecolor='green', 
                         edgecolor='darkgreen', linewidth=2, alpha=0.7)
    ax5.add_patch(box)
    ax5.text(x, 7.8, name, fontsize=8, fontweight='bold', 
            color='white', ha='center', va='center')
    ax5.text(x, 7, bonus, fontsize=11, fontweight='bold', 
            color='yellow', ha='center', va='center')

# Pénalités
penalty_items = [
    (77, "Blacklist", "-50%"),
    (87, "Vol. Mauvaise", "-70%"),
]

for x, name, penalty in penalty_items:
    box = FancyBboxPatch((x-3, 6), 6, 3, 
                         boxstyle="round,pad=0.1", 
                         facecolor='red', 
                         edgecolor='darkred', linewidth=2, alpha=0.7)
    ax5.add_patch(box)
    ax5.text(x, 7.8, name, fontsize=8, fontweight='bold', 
            color='white', ha='center', va='center')
    ax5.text(x, 7, penalty, fontsize=11, fontweight='bold', 
            color='yellow', ha='center', va='center')

# Seuil d'achat
threshold_box = FancyBboxPatch((40, 2), 20, 2.5, 
                              boxstyle="round,pad=0.15", 
                              facecolor=COLOR_SCORE, 
                              edgecolor='black', linewidth=3, alpha=0.9)
ax5.add_patch(threshold_box)
ax5.text(50, 3.5, "SEUIL D'ACHAT", fontsize=11, fontweight='bold', 
        color='white', ha='center', va='top')
ax5.text(50, 2.7, "Score ≥ 75", fontsize=14, fontweight='bold', 
        color='yellow', ha='center', va='center')

# Légende informative
info_text = """
🎯 OBJECTIF: Identifier les meilleures opportunités d'achat en temps réel
⚡ GPU: NVIDIA RTX 5060 Ti (PyTorch + CUDA 12.8)
🔄 CYCLE: Analyse toutes les 5 secondes
📊 DONNÉES: 100 bougies (prix + volume) par crypto
✅ QUALITÉ > QUANTITÉ: 1 bon trade (score 90) > 5 trades moyens (score 60)
"""

ax5.text(50, 0.5, info_text, fontsize=9, ha='center', va='center',
        bbox=dict(boxstyle='round', facecolor='lightyellow', alpha=0.8, pad=0.5))

# Sauvegarder
plt.savefig('ai_architecture_diagram.png', dpi=300, bbox_inches='tight', 
            facecolor='white', edgecolor='none')
print("✅ Diagramme généré: ai_architecture_diagram.png")

plt.close()
