"""
Appends a cumulative stats block to CHANGES_LOG.txt after each iteration.
Called by the scheduled task after iterate.py runs.
"""
import json, datetime, os

ANALYTICS_PATH = r"C:\kalshibot\Automated\trade_analytics.json"
BOT_STATE_PATH = r"C:\kalshibot\Automated\bot_state.json"
ITER_LOG_PATH  = r"C:\kalshibot\Automated\tracker\iteration_history.json"
CHANGES_LOG    = r"C:\kalshibot\Automated\tracker\CHANGES_LOG.txt"

def load(path, default):
    try:
        with open(path, encoding="utf-8") as f: return json.load(f)
    except: return default

analytics = load(ANALYTICS_PATH, [])
bot_state  = load(BOT_STATE_PATH, {})
iter_hist  = load(ITER_LOG_PATH,  [])

exits  = [t for t in analytics if t.get("event") == "exit"]
wins   = [t for t in exits if t.get("outcome") == "WIN"]
losses = [t for t in exits if t.get("outcome") == "LOSS"]
total_pnl = sum(t.get("pnl", 0) for t in exits)
wr = round(len(wins) / len(exits) * 100, 1) if exits else 0

iter_num = len(iter_hist)
balance  = bot_state.get("balance", 0)
btc      = bot_state.get("btc_price", 0)

# Build recent trades list
recent = exits[-10:] if len(exits) >= 10 else exits
trade_lines = ""
for t in recent:
    trade_lines += (
        f"  {t.get('time_str','?')} | EXP:{t.get('exp_score',0)} LAG:{t.get('lag_score',0)} "
        f"MOM:{t.get('mom_score',0)} | {t.get('entry_price',0):.3f}->{t.get('exit_price',0):.3f} "
        f"| {t.get('outcome','?')} ${t.get('pnl',0):+.2f} | {t.get('exit_reason','?')}\n"
    )

block = f"""
================================================================================
CUMULATIVE UPDATE — Iteration #{iter_num}
Time: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
================================================================================
CUMULATIVE TOTALS (across all restarts):
  Total trades  : {len(exits)}
  Wins          : {len(wins)}
  Losses        : {len(losses)}
  Win Rate      : {wr}%
  Total P&L     : ${total_pnl:+.4f}
  Balance now   : ${balance:.2f} (started $500)
  BTC Price     : ${btc:,.2f}

LAST {len(recent)} TRADES:
{trade_lines}
"""

with open(CHANGES_LOG, "a", encoding="utf-8") as f:
    f.write(block)

print(f"Stats written: {len(exits)} trades | {wr}% WR | ${total_pnl:+.4f} P&L | Balance ${balance:.2f}")
