#!/bin/bash
# Async backtest launcher - ALWAYS returns immediately
# The agent's exec tool has a 10-second timeout, so this script
# must never block. It launches the backtest in background and exits.
#
# Usage: bot_backtest.sh [period] [rows]
#
# Period options:
#   1month     - Latest 1 month only (~300MB) [DEFAULT]
#   2month     - Latest 2 months
#   3month     - Latest 3 months
#   6month     - Full 6-month file (2.1GB)
#   5year      - Full 5-year file (25GB)
#   202601     - Specific month
#   202510-202512 - Month range
#
# Default: 1month, 2000000 rows
# Monitor: bash bot_check.sh

cd /var/www/html/crpytotradingbot

PERIOD="${1:-1month}"
ROWS="${2:-2000000}"

# Safety cap
if [ "$ROWS" -gt 5000000 ] 2>/dev/null; then
    echo "ERROR: Max 5M rows. Use smaller period or fewer rows."
    exit 1
fi

# Kill any existing backtest to avoid zombies
EXISTING=$(pgrep -f "bot_runner.py" 2>/dev/null)
if [ -n "$EXISTING" ]; then
    kill $EXISTING 2>/dev/null
    sleep 0.5
    # Force kill if still alive
    kill -9 $EXISTING 2>/dev/null
    echo "Killed previous backtest (PID: $EXISTING)"
fi

# Determine timeout: longer for bigger datasets
case "$PERIOD" in
    5year)  TIMEOUT=3600 ;;
    6month) TIMEOUT=600 ;;
    3month) TIMEOUT=480 ;;
    *)      TIMEOUT=300 ;;
esac

# Launch in background - returns immediately
LOGFILE="/var/www/html/crpytotradingbot/results/bg_output_$(date +%Y%m%d_%H%M%S).txt"
nohup nice -n 15 python3 bot_runner.py \
    --csv="$PERIOD" \
    --max-rows=$ROWS \
    --timeout=$TIMEOUT \
    --throttle=2 \
    > "$LOGFILE" 2>&1 &

BG_PID=$!
echo "Backtest launched (PID: $BG_PID)"
echo "Period: $PERIOD, Rows: $ROWS, Timeout: ${TIMEOUT}s"
echo "Monitor: bash bot_check.sh"
echo "Log: $LOGFILE"
