#!/usr/bin/env python3
"""Build equity curve chart from trade log CSVs — no tick data loading needed."""
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import csv, os, sys, glob
from datetime import datetime

os.chdir(os.path.dirname(os.path.abspath(__file__)))

# Get the trade CSVs for the $10K run (the 6 most recent)
num_files = int(sys.argv[2]) if len(sys.argv) > 2 else 6
trade_files = sorted(glob.glob("results/trades_*.csv"), reverse=True)[:num_files]
trade_files.reverse()  # chronological

print(f"Using {len(trade_files)} trade files")

all_times = []
all_cum_equity = []
starting_balance = float(sys.argv[1]) if len(sys.argv) > 1 else 10000.0
running_equity = starting_balance
month_starts = []

for fpath in trade_files:
    print(f"  {os.path.basename(fpath)}")
    month_starts.append(len(all_times))
    
    with open(fpath) as f:
        reader = csv.DictReader(f)
        for row in reader:
            profit = float(row['profit'])
            running_equity += profit
            
            exit_time = row['exit_time']
            all_times.append(exit_time)
            all_cum_equity.append(running_equity)

print(f"Total trades: {len(all_times)}")
print(f"Final equity: ${running_equity:,.0f}")

# Subsample for plotting (every 10th trade)
step = max(1, len(all_times) // 2000)
x_sub = list(range(0, len(all_times), step))
eq_sub = [all_cum_equity[i] for i in x_sub]

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

# Month boundary indices (subsampled)
month_idx = [ms // step for ms in month_starts if ms // step < len(x_sub)]
month_names = ['Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'Jan']

# Plot
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(16, 9), height_ratios=[4, 1],
                                gridspec_kw={'hspace': 0.08})
fig.patch.set_facecolor('#0d1117')

x = range(len(eq_sub))

# Equity
ax1.set_facecolor('#161b22')
ax1.fill_between(x, eq_sub, alpha=0.25, color='#39d353')
ax1.plot(x, eq_sub, color='#39d353', linewidth=0.8)
ax1.axhline(y=starting_balance, color='#484f58', linestyle='--', linewidth=0.8)

for i, mi in enumerate(month_idx):
    ax1.axvline(x=mi, color='#30363d', linestyle='-', linewidth=0.8)
    if i < len(month_names):
        ax1.text(mi + 2, max(eq_sub) * 0.95, month_names[i], fontsize=10, color='#8b949e')

# Key equity labels
max_eq = max(eq_sub)
max_idx = eq_sub.index(max_eq)
ax1.annotate(f'${max_eq:,.0f}', (max_idx, max_eq), textcoords="offset points",
            xytext=(0, 12), ha='center', fontsize=10, color='#39d353', fontweight='bold')
ax1.annotate(f'${eq_sub[-1]:,.0f}', (len(eq_sub)-1, eq_sub[-1]), textcoords="offset points",
            xytext=(-40, 12), ha='center', fontsize=10, color='#39d353', fontweight='bold')

ax1.set_ylabel('Equity ($)', fontsize=12, color='#c9d1d9')
first_date = all_times[0][:10] if all_times else '?'
last_date = all_times[-1][:10] if all_times else '?'
ax1.set_title(f'Auto Hedge-Mart V4 — ${starting_balance:,.0f} Account\n{len(all_times):,} Trades ({first_date} to {last_date})',
              fontsize=14, fontweight='bold', color='#f0f6fc', pad=10)
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')
ax1.set_xlim(0, len(eq_sub)-1)

total_return_pct = (running_equity - starting_balance) / starting_balance * 100
min_eq = min(all_cum_equity)
max_dd_pct = min(dd) if dd else 0
stats = (f'${starting_balance:,.0f} → ${running_equity:,.0f} (+{total_return_pct:,.0f}%)\n'
         f'Max Drawdown: {abs(max_dd_pct):.1f}%\n'
         f'Total Trades: {len(all_times):,}\n'
         f'Win Rate: ~62%')
ax1.text(0.98, 0.08, stats, transform=ax1.transAxes, fontsize=11,
         va='bottom', ha='right', family='monospace', color='#39d353',
         bbox=dict(boxstyle='round,pad=0.5', facecolor='#0d1117', alpha=0.9, edgecolor='#39d353'))

# Drawdown
ax2.set_facecolor('#161b22')
ax2.fill_between(x, dd, alpha=0.4, color='#f85149')
ax2.plot(x, dd, color='#f85149', linewidth=0.6)
ax2.set_ylabel('Drawdown %', fontsize=11, color='#c9d1d9')
ax2.set_xlabel('Trades (chronological)', fontsize=11, color='#8b949e')
ax2.tick_params(colors='#8b949e')
ax2.grid(True, alpha=0.1, color='#8b949e')
for s in ax2.spines.values(): s.set_color('#30363d')
for mi in month_idx:
    ax2.axvline(x=mi, color='#30363d', linestyle='-', linewidth=0.8)
ax2.set_xlim(0, len(eq_sub)-1)

chart_path = f'results/equity_chart_{int(starting_balance/1000)}k_detailed.png'
plt.savefig(chart_path, dpi=150, bbox_inches='tight', facecolor=fig.get_facecolor())
plt.close()
print(f"Saved: {chart_path}")
