#!/usr/bin/env python3
"""
Generate chart by polling progress.json during a live backtest run.
Run this WHILE a backtest is running. It captures equity snapshots.

Usage: python3 gen_chart_from_progress.py <snapshots_file>
"""
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import json, sys

# Load snapshots from file
snapshots_file = sys.argv[1] if len(sys.argv) > 1 else "results/equity_snapshots.json"

with open(snapshots_file) as f:
    data = json.load(f)

equity = [d['equity'] for d in data]
prices = [d['price'] for d in data]
dates = [d.get('date', '') for d in data]
months = [d.get('month', '') for d in data]

# Drawdown
peak = [equity[0]]
for e in equity[1:]:
    peak.append(max(peak[-1], e))
dd = [(e - p) / p * 100 if p > 0 else 0 for e, p in zip(equity, peak)]

# Plot
fig, axes = plt.subplots(3, 1, figsize=(16, 10), height_ratios=[4, 1.5, 1],
                          gridspec_kw={'hspace': 0.08})
fig.patch.set_facecolor('#0d1117')

x = range(len(equity))

ax1 = axes[0]
ax1.set_facecolor('#161b22')
ax1.fill_between(x, equity, alpha=0.25, color='#39d353')
ax1.plot(x, equity, color='#39d353', linewidth=1)
ax1.axhline(y=equity[0], color='#484f58', linestyle='--', linewidth=0.8)
ax1.set_ylabel('Equity ($)', fontsize=11, color='#c9d1d9')
ax1.set_title(f'Auto Hedge-Mart V4 — Equity Curve\n${equity[0]:,.0f} → ${equity[-1]:,.0f}',
              fontsize=13, fontweight='bold', color='#f0f6fc')
ax1.yaxis.set_major_formatter(mticker.FuncFormatter(lambda x, p: f'${x:,.0f}'))
ax1.tick_params(colors='#8b949e')
ax1.grid(True, alpha=0.1, color='#8b949e')
for s in ax1.spines.values(): s.set_color('#30363d')

ax2 = axes[1]
ax2.set_facecolor('#161b22')
ax2.plot(x, prices, color='#f0883e', linewidth=1)
ax2.fill_between(x, prices, alpha=0.15, color='#f0883e')
ax2.set_ylabel('BTC ($)', fontsize=10, color='#c9d1d9')
ax2.yaxis.set_major_formatter(mticker.FuncFormatter(lambda x, p: f'${x:,.0f}'))
ax2.tick_params(colors='#8b949e')
ax2.grid(True, alpha=0.1, color='#8b949e')
for s in ax2.spines.values(): s.set_color('#30363d')

ax3 = axes[2]
ax3.set_facecolor('#161b22')
ax3.fill_between(x, dd, alpha=0.4, color='#f85149')
ax3.plot(x, dd, color='#f85149', linewidth=0.8)
ax3.set_ylabel('DD %', fontsize=10, color='#c9d1d9')
ax3.tick_params(colors='#8b949e')
ax3.grid(True, alpha=0.1, color='#8b949e')
for s in ax3.spines.values(): s.set_color('#30363d')

chart_path = '/var/www/html/crpytotradingbot/results/equity_chart_10k_detailed.png'
plt.savefig(chart_path, dpi=150, bbox_inches='tight', facecolor=fig.get_facecolor())
plt.close()
print(f"Saved: {chart_path}")
