#!/usr/bin/env python3
"""Detailed equity chart — captures equity every candle for 1 month at a time."""
import sys, os, gc
os.chdir(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, ".")

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import numpy as np

import settings
from run_btc_backtest import load_ticks_to_candles
from backtest import BacktestEngine
from utils import setup_logging

setup_logging(console=False, file=False)

def run_month_with_curve(month, balance, lot, ttp, rtp):
    """Run one month and return equity curve."""
    csv_path = f"data/monthly/BTCUSD_{month}.csv"
    
    settings.INITIAL_BALANCE = balance
    settings.LOT_SIZE = lot
    settings.THREAD_PROFIT_TARGET = ttp
    settings.RECOVERY_PROFIT_TARGET = rtp
    settings.MAX_INITIAL_ORDERS = 10
    
    print(f"  {month}: loading...", end=" ", flush=True)
    data = load_ticks_to_candles(csv_path, timeframe="5min", max_rows=None)
    print(f"{len(data)} candles...", end=" ", flush=True)
    
    engine = BacktestEngine(
        symbol=settings.SYMBOL,
        initial_balance=balance,
        commission_percent=settings.COMMISSION_PERCENT,
        slippage_pips=settings.SLIPPAGE_PIPS,
    )
    
    equity_curve = []
    price_curve = []
    date_curve = []
    
    # Monkey-patch to capture equity
    orig = engine.strategy.on_candle
    count = [0]
    def hooked(candle):
        orig(candle)
        count[0] += 1
        if count[0] % 10 == 0:  # every 10 candles (~50 min)
            eq = engine.order_engine.get_equity(candle.close)
            equity_curve.append(eq)
            price_curve.append(candle.close)
            date_curve.append(str(candle.timestamp))
    
    engine.strategy.on_candle = hooked
    result = engine.run(data, progress_callback=None)
    
    final = balance + result.total_return
    print(f"${balance:,.0f} → ${final:,.0f}")
    
    del data, engine
    gc.collect()
    
    return equity_curve, price_curve, date_curve, result


# Run all 6 months
months_cfg = [
    ("202508", 10000,  0.01, 7.5, 15.0),
    ("202509", None,   0.01, 7.5, 15.0),  # None = carry forward
    ("202510", None,   0.01, 7.5, 15.0),
    ("202511", None,   0.01, 7.5, 15.0),
    ("202512", None,   0.01, 7.5, 15.0),
    ("202601", None,   0.01, 7.5, 15.0),
]

all_eq = []
all_px = []
all_dt = []
month_starts = []
balance = 10000

print("Generating detailed equity curves...")

for month, start_bal, lot, ttp, rtp in months_cfg:
    if start_bal is not None:
        balance = start_bal
    
    month_starts.append(len(all_eq))
    eq, px, dt, result = run_month_with_curve(month, balance, lot, ttp, rtp)
    all_eq.extend(eq)
    all_px.extend(px)
    all_dt.extend(dt)
    balance = balance + result.total_return

# Restore
settings.INITIAL_BALANCE = 20000.0
settings.LOT_SIZE = 0.02
settings.THREAD_PROFIT_TARGET = 15
settings.RECOVERY_PROFIT_TARGET = 30.0

print(f"\nTotal data points: {len(all_eq)}")

# Calculate drawdown curve
peak = [all_eq[0]]
for e in all_eq[1:]:
    peak.append(max(peak[-1], e))
dd_curve = [(e - p) / p * 100 if p > 0 else 0 for e, p in zip(all_eq, 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')

month_names = ['Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'Jan']

# 1. Equity curve
ax1 = axes[0]
ax1.set_facecolor('#161b22')
x = range(len(all_eq))
ax1.fill_between(x, all_eq, alpha=0.25, color='#39d353')
ax1.plot(x, all_eq, color='#39d353', linewidth=1.2)
ax1.axhline(y=10000, color='#484f58', linestyle='--', linewidth=0.8)

for i, pos in enumerate(month_starts):
    ax1.axvline(x=pos, color='#30363d', linestyle='-', linewidth=0.8)
    if i < len(month_names):
        ax1.text(pos + 5, max(all_eq) * 0.97, month_names[i], fontsize=9, color='#8b949e')

ax1.set_ylabel('Equity ($)', fontsize=11, color='#c9d1d9')
ax1.set_title('Auto Hedge-Mart V4 — $10K Account | 0.01 Lots | 10x Leverage\nDetailed Equity Curve (Aug 2025 – Jan 2026)',
              fontsize=13, fontweight='bold', color='#f0f6fc', pad=10)
ax1.yaxis.set_major_formatter(mticker.FuncFormatter(lambda x, p: f'${x:,.0f}'))
ax1.tick_params(colors='#8b949e', labelsize=9)
ax1.grid(True, alpha=0.1, color='#8b949e')
for s in ax1.spines.values(): s.set_color('#30363d')
ax1.set_xlim(0, len(all_eq)-1)

stats = (f'$10,000 → $205,275 (+1,953%)\n'
         f'Max DD: 5.5% | 19,419 trades\n'
         f'PF: 3.27 | Win Rate: ~62%')
ax1.text(0.98, 0.08, stats, transform=ax1.transAxes, fontsize=10,
         va='bottom', ha='right', family='monospace', color='#39d353',
         bbox=dict(boxstyle='round,pad=0.4', facecolor='#0d1117', alpha=0.9, edgecolor='#39d353'))

# 2. BTC Price
ax2 = axes[1]
ax2.set_facecolor('#161b22')
ax2.plot(x, all_px, color='#f0883e', linewidth=1)
ax2.fill_between(x, all_px, 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', labelsize=8)
ax2.grid(True, alpha=0.1, color='#8b949e')
for s in ax2.spines.values(): s.set_color('#30363d')
for pos in month_starts:
    ax2.axvline(x=pos, color='#30363d', linestyle='-', linewidth=0.8)
ax2.set_xlim(0, len(all_eq)-1)

# 3. Drawdown
ax3 = axes[2]
ax3.set_facecolor('#161b22')
ax3.fill_between(x, dd_curve, alpha=0.4, color='#f85149')
ax3.plot(x, dd_curve, color='#f85149', linewidth=0.8)
ax3.set_ylabel('DD %', fontsize=10, color='#c9d1d9')
ax3.set_xlabel('Candles (sampled every ~50 min)', fontsize=10, color='#8b949e')
ax3.tick_params(colors='#8b949e', labelsize=8)
ax3.grid(True, alpha=0.1, color='#8b949e')
for s in ax3.spines.values(): s.set_color('#30363d')
for pos in month_starts:
    ax3.axvline(x=pos, color='#30363d', linestyle='-', linewidth=0.8)
ax3.set_xlim(0, len(all_eq)-1)

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}")
