import pandas as pd
import plotly.graph_objects as go
from jinja2 import Template
import json
import datetime

# === CONFIGURATION ===
SUMMARY_FILE = "user_data/backtest_results/result.json"  # chemin vers ton JSON
BALANCE_HISTORY_FILE = "user_data/backtest_results/backtest_result.json"  # ou fichier contenant le portefeuille

# === CHARGEMENT DES DONNÉES ===
with open(SUMMARY_FILE, "r") as f:
    summary = json.load(f)

df_summary = pd.DataFrame([summary])
start = summary.get("backtest_start", "")
end = summary.get("backtest_end", "")
final_balance = summary.get("final_balance", 0)

# === AFFICHAGE DES ÉVOLUTIONS DE BALANCE ===
result = pd.read_json(BALANCE_HISTORY_FILE)
result["date"] = pd.to_datetime(result["date"])
balance_trace = go.Scatter(
    x=result["date"],
    y=result["balance"],
    mode="lines",
    name="Balance",
    line=dict(color="green")
)

layout = go.Layout(
    title="Évolution du portefeuille",
    xaxis_title="Date",
    yaxis_title="Balance (USDT)",
    template="plotly_white"
)

fig = go.Figure(data=[balance_trace], layout=layout)
fig.write_html("balance_plot.html", include_plotlyjs="cdn")

# === GÉNÉRATION DU RAPPORT HTML ===
template_str = """
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Rapport de Backtest</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 40px; }
        table { border-collapse: collapse; width: 80%; margin-bottom: 40px; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        th { background-color: #f2f2f2; }
        h1, h2 { color: #333; }
    </style>
</head>
<body>
    <h1>Rapport de Backtest</h1>
    <h2>Période : {{ start }} → {{ end }}</h2>
    <table>
        <tr><th>Métrique</th><th>Valeur</th></tr>
        {% for key, value in metrics.items() %}
            <tr><td>{{ key }}</td><td>{{ value }}</td></tr>
        {% endfor %}
    </table>
    <h2>Évolution de la balance</h2>
    <iframe src="balance_plot.html" width="1000" height="600" frameborder="0"></iframe>
</body>
</html>
"""

metrics = {
    "Trading Mode": summary.get("strategy", ""),
    "Total Trades": summary.get("total_trades", 0),
    "Final Balance": f"{final_balance:.2f} USDT",
    "Profit (%)": f"{summary.get('profit_total_pct', 0):.2f}%",
    "CAGR": f"{summary.get('cagr', 0):.2f}%",
    "Sharpe": summary.get("sharpe", ""),
    "Sortino": summary.get("sortino", ""),
    "SQN": summary.get("sqn", ""),
    "Calmar": summary.get("calmar", ""),
    "Best Pair": summary.get("best_pair", ""),
    "Worst Pair": summary.get("worst_pair", ""),
    "Max Drawdown": summary.get("max_drawdown", ""),
}

template = Template(template_str)
html_content = template.render(start=start, end=end, metrics=metrics)

with open("backtest_report.html", "w") as f:
    f.write(html_content)

print("✅ Rapport généré : backtest_report.html")
