#!/bin/bash
# Check backtest progress + detect zombie processes
# Returns quickly - safe for agent exec tool (10s timeout)
PROGRESS="/var/www/html/crpytotradingbot/backtest_progress.json"

# Check if bot_runner is actually running
RUNNING_PID=$(pgrep -f "bot_runner.py" 2>/dev/null)

if [ ! -f "$PROGRESS" ]; then
    if [ -n "$RUNNING_PID" ]; then
        echo "Status: RUNNING (no progress file yet, PID: $RUNNING_PID)"
    else
        echo "No backtest in progress"
    fi
    exit 0
fi

# Read progress with python
python3 -c "
import json, os, time
with open('$PROGRESS') as f:
    d = json.load(f)
s = d.get('status', 'unknown')
updated = d.get('updated_at', '')

# Check staleness - if progress hasn't updated in 60s but status is 'running', it's stuck
stale = False
if updated and s == 'running':
    from datetime import datetime
    try:
        last = datetime.fromisoformat(updated)
        age = (datetime.now() - last).total_seconds()
        if age > 60:
            stale = True
            print(f'WARNING: Progress stale ({age:.0f}s old) - backtest may be stuck')
    except:
        pass

if s == 'running':
    print(f\"Status: RUNNING ({d.get('pct',0)}% done)\")
    print(f\"Candles: {d.get('processed',0):,} / {d.get('total',0):,}\")
    print(f\"Balance: \${d.get('balance',0):,.2f}  Equity: \${d.get('equity',0):,.2f}\")
    print(f\"Return: {d.get('return_pct',0):+.2f}%  MaxDD: {d.get('max_dd_pct',0):.2f}%\")
    print(f\"Trades: {d.get('trades',0):,}  Open positions: {d.get('open_positions',0)}\")
    print(f\"Price: \${d.get('current_price',0):,.2f}  Date: {d.get('current_date','?')}\")
    print(f\"Speed: {d.get('candles_per_sec',0):.0f} candles/sec  ETA: {d.get('eta_sec',0):.0f}s\")
elif s == 'complete':
    print(f\"Status: COMPLETE in {d.get('elapsed_sec',0):.0f}s\")
    print(f\"Net: \${d.get('net_profit',0):,.2f} ({d.get('return_pct',0):+.2f}%)\")
    print(f\"Trades: {d.get('total_trades',0):,}  WR: {d.get('win_rate',0):.1f}%\")
    print(f\"PF: {d.get('profit_factor',0):.2f}  MaxDD: {d.get('max_dd_pct',0):.2f}%\")
    print(f\"Period: {d.get('date_start','?')} to {d.get('date_end','?')}\")
    print(f\"Gross profit: \${d.get('gross_profit',0):,.2f}  Gross loss: \${d.get('gross_loss',0):,.2f}\")
    print(f\"Threads: {d.get('total_threads',0)}  Max recovery: L{d.get('max_recovery_level',0)}\")
elif s == 'loading':
    print(f\"Status: LOADING data... {d.get('message','')}\")
elif s == 'resampling':
    print(f\"Status: RESAMPLING {d.get('ticks_loaded',0):,} ticks...\")
elif s == 'error':
    print(f\"Status: ERROR - {d.get('error','unknown')}\")
elif s == 'timeout':
    print(f\"Status: TIMED OUT\")
elif s == 'interrupted':
    print(f\"Status: INTERRUPTED - {d.get('message','')}\")
else:
    print(f\"Status: {s}\")
    print(json.dumps(d, indent=2))
" 2>/dev/null

# Show PID if running
if [ -n "$RUNNING_PID" ]; then
    echo "PID: $RUNNING_PID"
fi
