#!/usr/bin/env python3
"""
Web Dashboard pour Martingale Degen Bot
Affiche les résultats du backtest dans une interface web
"""

from flask import Flask, render_template_string
import json
from datetime import datetime

app = Flask(__name__)

HTML_TEMPLATE = """
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>🎲 Martingale Degen - Résultats</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: #fff;
            padding: 20px;
            min-height: 100vh;
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
        }

        .header {
            text-align: center;
            padding: 40px 0;
            background: rgba(0, 0, 0, 0.3);
            border-radius: 20px;
            margin-bottom: 30px;
            backdrop-filter: blur(10px);
        }

        .header h1 {
            font-size: 3em;
            margin-bottom: 10px;
            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
        }

        .header .subtitle {
            font-size: 1.2em;
            opacity: 0.9;
        }

        .warning {
            background: rgba(255, 59, 48, 0.2);
            border: 2px solid #ff3b30;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 30px;
            text-align: center;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .stat-card {
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            border-radius: 15px;
            padding: 25px;
            text-align: center;
            transition: transform 0.3s, box-shadow 0.3s;
            border: 1px solid rgba(255, 255, 255, 0.2);
        }

        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
        }

        .stat-card .label {
            font-size: 0.9em;
            opacity: 0.8;
            margin-bottom: 10px;
            text-transform: uppercase;
            letter-spacing: 1px;
        }

        .stat-card .value {
            font-size: 2.5em;
            font-weight: bold;
            margin-bottom: 5px;
        }

        .stat-card.positive .value {
            color: #4ade80;
        }

        .stat-card.negative .value {
            color: #f87171;
        }

        .stat-card.neutral .value {
            color: #fbbf24;
        }

        .trades-section {
            background: rgba(0, 0, 0, 0.3);
            border-radius: 20px;
            padding: 30px;
            margin-bottom: 30px;
            backdrop-filter: blur(10px);
        }

        .trades-section h2 {
            font-size: 2em;
            margin-bottom: 20px;
            text-align: center;
        }

        .trades-table {
            width: 100%;
            border-collapse: separate;
            border-spacing: 0 10px;
        }

        .trades-table thead th {
            background: rgba(255, 255, 255, 0.1);
            padding: 15px;
            text-align: left;
            font-weight: 600;
            text-transform: uppercase;
            font-size: 0.85em;
            letter-spacing: 1px;
        }

        .trades-table tbody tr {
            background: rgba(255, 255, 255, 0.05);
            transition: background 0.3s;
        }

        .trades-table tbody tr:hover {
            background: rgba(255, 255, 255, 0.1);
        }

        .trades-table tbody td {
            padding: 15px;
            border-top: 1px solid rgba(255, 255, 255, 0.1);
        }

        .badge {
            display: inline-block;
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 0.85em;
            font-weight: 600;
        }

        .badge.long {
            background: rgba(74, 222, 128, 0.2);
            color: #4ade80;
            border: 1px solid #4ade80;
        }

        .badge.short {
            background: rgba(248, 113, 113, 0.2);
            color: #f87171;
            border: 1px solid #f87171;
        }

        .badge.tp {
            background: rgba(34, 197, 94, 0.2);
            color: #22c55e;
        }

        .badge.sl {
            background: rgba(239, 68, 68, 0.2);
            color: #ef4444;
        }

        .badge.timeout {
            background: rgba(251, 191, 36, 0.2);
            color: #fbbf24;
        }

        .pnl-positive {
            color: #4ade80;
            font-weight: 600;
        }

        .pnl-negative {
            color: #f87171;
            font-weight: 600;
        }

        .martingale-level {
            display: inline-block;
            padding: 4px 10px;
            background: rgba(167, 139, 250, 0.3);
            border-radius: 10px;
            font-weight: 600;
        }

        .footer {
            text-align: center;
            padding: 30px;
            opacity: 0.7;
            font-size: 0.9em;
        }

        @media (max-width: 768px) {
            .header h1 {
                font-size: 2em;
            }

            .stats-grid {
                grid-template-columns: 1fr;
            }

            .trades-table {
                font-size: 0.85em;
            }
        }

        .emoji {
            font-size: 1.2em;
        }

        .chart-container {
            background: rgba(0, 0, 0, 0.3);
            border-radius: 20px;
            padding: 30px;
            margin-bottom: 30px;
            backdrop-filter: blur(10px);
        }

        .equity-curve {
            width: 100%;
            height: 300px;
            background: rgba(255, 255, 255, 0.05);
            border-radius: 10px;
            position: relative;
            overflow: hidden;
        }

        .equity-line {
            stroke: #4ade80;
            stroke-width: 3;
            fill: none;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🎲 Martingale Degen Bot</h1>
            <p class="subtitle">Résultats du Backtest - {{ symbol }} {{ timeframe }}</p>
            <p style="opacity: 0.7; margin-top: 10px;">{{ start_date }} → {{ end_date }}</p>
        </div>

        <div class="warning">
            <strong>⚠️ AVERTISSEMENT:</strong> Backtest avec leverage jusqu'à 1000x - Résultats à titre éducatif uniquement
        </div>

        <div class="stats-grid">
            <div class="stat-card {% if total_return_pct > 0 %}positive{% else %}negative{% endif %}">
                <div class="label">Retour Total</div>
                <div class="value">{{ "%.2f"|format(total_return_pct) }}%</div>
                <div>${{ "%.2f"|format(final_capital) }}</div>
            </div>

            <div class="stat-card neutral">
                <div class="label">Win Rate</div>
                <div class="value">{{ "%.1f"|format(win_rate * 100) }}%</div>
                <div>{{ winning_trades }}/{{ total_trades }} trades</div>
            </div>

            <div class="stat-card {% if profit_factor > 1 %}positive{% else %}negative{% endif %}">
                <div class="label">Profit Factor</div>
                <div class="value">{{ "%.2f"|format(profit_factor) }}</div>
                <div>Risk/Reward Ratio</div>
            </div>

            <div class="stat-card negative">
                <div class="label">Max Drawdown</div>
                <div class="value">{{ "%.2f"|format(max_drawdown_pct) }}%</div>
                <div>Pire baisse</div>
            </div>

            <div class="stat-card positive">
                <div class="label">Gain Moyen</div>
                <div class="value">+{{ "%.2f"|format(avg_win_pct) }}%</div>
                <div>Par trade gagnant</div>
            </div>

            <div class="stat-card negative">
                <div class="label">Perte Moyenne</div>
                <div class="value">{{ "%.2f"|format(avg_loss_pct) }}%</div>
                <div>Par trade perdant</div>
            </div>

            <div class="stat-card neutral">
                <div class="label">Max Martingale</div>
                <div class="value">L{{ max_martingale_level_reached }}</div>
                <div>x{{ 2**max_martingale_level_reached }} position</div>
            </div>

            <div class="stat-card negative">
                <div class="label">Pertes Consécutives</div>
                <div class="value">{{ max_consecutive_losses }}</div>
                <div>Maximum streak</div>
            </div>
        </div>

        <div class="trades-section">
            <h2>📊 Historique des Trades ({{ total_trades }} total)</h2>
            <div style="overflow-x: auto;">
                <table class="trades-table">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>Côté</th>
                            <th>Entry</th>
                            <th>Exit</th>
                            <th>SL / TP</th>
                            <th>PnL %</th>
                            <th>PnL $</th>
                            <th>Sortie</th>
                            <th>Level</th>
                            <th>Leverage</th>
                            <th>Durée</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for trade in trades %}
                        <tr>
                            <td>{{ loop.index }}</td>
                            <td><span class="badge {{ trade.side|lower }}">{{ trade.side }}</span></td>
                            <td>${{ "%.2f"|format(trade.entry_price) }}</td>
                            <td>${{ "%.2f"|format(trade.exit_price) }}</td>
                            <td style="font-size: 0.85em;">
                                ${{ "%.2f"|format(trade.stop_loss) }}<br>
                                ${{ "%.2f"|format(trade.take_profit) }}
                            </td>
                            <td class="{% if trade.pnl_pct > 0 %}pnl-positive{% else %}pnl-negative{% endif %}">
                                {{ "%+.2f"|format(trade.pnl_pct) }}%
                            </td>
                            <td class="{% if trade.pnl_usd > 0 %}pnl-positive{% else %}pnl-negative{% endif %}">
                                ${{ "%+.2f"|format(trade.pnl_usd) }}
                            </td>
                            <td><span class="badge {{ trade.exit_reason|lower }}">{{ trade.exit_reason }}</span></td>
                            <td><span class="martingale-level">L{{ trade.martingale_level }}</span></td>
                            <td><strong>{{ trade.leverage }}x</strong></td>
                            <td>{{ trade.duration_minutes }}m</td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>

        <div class="footer">
            <p>🎲 Martingale Degen Bot - Backtest généré le {{ now }}</p>
            <p style="margin-top: 10px;">⚠️ Système ultra-risqué - Trading éducatif uniquement</p>
        </div>
    </div>
</body>
</html>
"""

@app.route('/')
def dashboard():
    """Affiche le dashboard avec les résultats du backtest"""
    try:
        # Charger les résultats
        with open('martingale_results.json', 'r') as f:
            data = json.load(f)

        # Préparer les données pour le template
        context = {
            'symbol': data['symbol'],
            'timeframe': data['timeframe'],
            'start_date': data['start_date'][:19],
            'end_date': data['end_date'][:19],
            'initial_capital': data['initial_capital'],
            'final_capital': data['final_capital'],
            'total_return_pct': data['total_return_pct'],
            'total_trades': data['total_trades'],
            'winning_trades': data['winning_trades'],
            'losing_trades': data['losing_trades'],
            'win_rate': data['win_rate'],
            'avg_win_pct': data['avg_win_pct'],
            'avg_loss_pct': data['avg_loss_pct'],
            'largest_win_pct': data['largest_win_pct'],
            'largest_loss_pct': data['largest_loss_pct'],
            'profit_factor': data['profit_factor'],
            'max_drawdown_pct': data['max_drawdown_pct'],
            'max_consecutive_losses': data['max_consecutive_losses'],
            'max_martingale_level_reached': data['max_martingale_level_reached'],
            'total_fees_usd': data['total_fees_usd'],
            'trades': data['trades'],
            'now': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        }

        return render_template_string(HTML_TEMPLATE, **context)

    except FileNotFoundError:
        return """
        <html>
        <body style="font-family: Arial; text-align: center; padding: 50px;">
            <h1>❌ Erreur</h1>
            <p>Fichier martingale_results.json introuvable</p>
            <p>Lancez d'abord le backtest:</p>
            <code>python3 martingale_backtester.py</code>
        </body>
        </html>
        """, 404

if __name__ == '__main__':
    print("\n" + "="*80)
    print("🌐 MARTINGALE DEGEN - WEB DASHBOARD")
    print("="*80)
    print("\n✅ Serveur démarré!")
    print(f"📊 Dashboard accessible sur: http://localhost:5000")
    print("\n⚠️  Appuyez sur Ctrl+C pour arrêter\n")

    app.run(host='0.0.0.0', port=5000, debug=False)
