#!/usr/bin/env python3
"""Run ETH backtest chain — month by month with compounding."""
import os, sys, json, subprocess, glob, csv, time, re
os.chdir(os.path.dirname(os.path.abspath(__file__)))

SETTINGS_FILE = "settings.py"
RESULTS_DIR = "results"
ETH_DIR = "data/monthly_eth"

# Months to test (skip Nov - only 185K ticks, partial)
MONTHS = [
    ("202404", 0), ("202405", 0), ("202406", 0), ("202407", 0),
    ("202408", 2000000), ("202409", 0), ("202410", 0),
]

START = 20000.0

def write_setting(key, value):
    with open(SETTINGS_FILE) as f: text = f.read()
    if isinstance(value, bool): val = "True" if value else "False"
    else: val = str(value)
    text = re.sub(rf'^{key}\s*=\s*.*$', f'{key} = {val}', text, flags=re.MULTILINE)
    with open(SETTINGS_FILE, 'w') as f: f.write(text)

def get_peak_notional():
    files = sorted(glob.glob(os.path.join(RESULTS_DIR, "trades_*.csv")), reverse=True)
    if not files: return 0
    events = []
    with open(files[0]) as f:
        for row in csv.DictReader(f):
            n = float(row['lots']) * float(row['entry_price'])
            events.append(('o', row['entry_time'], n))
            events.append(('c', row['exit_time'], -n))
    events.sort(key=lambda x: x[1])
    mx = rn = 0
    for _, _, n in events:
        rn += n
        if rn > mx: mx = rn
    return mx

equity = START
peak_overall = 0
print(f"ETH BACKTEST CHAIN — LOT=0.15, TTP=15, MO=10, Hyperliquid")
print(f"Starting: ${equity:,.0f}")
print("=" * 80)

for month, max_rows in MONTHS:
    csv_path = f"{ETH_DIR}/ETHUSD_{month}.csv"
    if not os.path.exists(csv_path):
        print(f"  {month}: FILE NOT FOUND")
        continue
    
    write_setting("INITIAL_BALANCE", equity)
    
    cmd = [sys.executable, "bot_runner.py", f"--csv={csv_path}",
           f"--max-rows={max_rows}", "--tf=5min", "--throttle=0", "--timeout=600"]
    t0 = time.time()
    subprocess.run(cmd, capture_output=True, timeout=660)
    elapsed = time.time() - t0
    
    # Read result
    result_files = sorted(glob.glob(os.path.join(RESULTS_DIR, "result_*.json")), reverse=True)
    if not result_files: 
        print(f"  {month}: NO RESULT"); continue
    with open(result_files[0]) as f: data = json.load(f)
    if data.get("status","").lower() != "complete":
        print(f"  {month}: FAILED"); continue
    
    peak = get_peak_notional()
    peak_overall = max(peak_overall, peak)
    new_eq = equity + data["net_profit"]
    
    label = f"20{month[2:4]}-{month[4:6]}"
    print(f"  {label}: ${equity:>12,.0f} → ${new_eq:>12,.0f} ({data['return_pct']:>+8.1f}%) "
          f"DD:{data['max_dd_pct']:.1f}% PF:{data['profit_factor']:.2f} "
          f"Trades:{data['total_trades']:,} Peak:${peak:,.0f} [{elapsed:.0f}s]")
    
    equity = new_eq

total_ret = (equity / START - 1) * 100
print(f"\n{'='*80}")
print(f"FINAL: ${START:,.0f} → ${equity:,.0f} (+{total_ret:,.0f}%)")
print(f"Peak notional: ${peak_overall:,.0f}")
for a in [15000, 20000, 25000, 30000, 40000, 50000]:
    p = peak_overall / (a*50) * 100
    s = '✅' if p <= 85 else ('⚠️' if p <= 100 else '❌')
    print(f"  ${a:,} @ 50x → {p:.0f}% {s}")
