#!/bin/bash
# Run 6-month backtest month by month, carrying equity forward
# Usage: bash run_monthly_chain.sh [starting_balance]
# Results written to results/monthly_chain_TIMESTAMP.log
# Progress in backtest_progress.json

cd /var/www/html/crpytotradingbot

BALANCE="${1:-20000}"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
LOGFILE="results/monthly_chain_${TIMESTAMP}.log"
MONTHS="202508 202509 202510 202511 202512 202601"

mkdir -p results

echo "═══════════════════════════════════════════════════" | tee "$LOGFILE"
echo "  6-MONTH CHAIN RUN — $(date)" | tee -a "$LOGFILE"
echo "  Config: LOT=$(grep '^LOT_SIZE' settings.py | head -1)" | tee -a "$LOGFILE"
echo "  $(grep '^THREAD_PROFIT_TARGET' settings.py)" | tee -a "$LOGFILE"
echo "  $(grep '^RECOVERY_PROFIT_TARGET' settings.py)" | tee -a "$LOGFILE"
echo "  $(grep '^MAX_INITIAL_ORDERS' settings.py)" | tee -a "$LOGFILE"
echo "  Starting balance: \$${BALANCE}" | tee -a "$LOGFILE"
echo "═══════════════════════════════════════════════════" | tee -a "$LOGFILE"

WORST_DD="0"
TOTAL_TRADES=0

for MONTH in $MONTHS; do
    echo "" | tee -a "$LOGFILE"
    echo "──── MONTH: $MONTH | Start: \$${BALANCE} ────" | tee -a "$LOGFILE"
    
    # Update INITIAL_BALANCE in settings.py temporarily
    sed -i "s/^INITIAL_BALANCE = .*/INITIAL_BALANCE = ${BALANCE}/" settings.py
    
    # Run this month (inline, no timeout issues with single month)
    OUTPUT=$(nice -n 15 python3 bot_runner.py --csv="$MONTH" --max-rows=0 --timeout=600 --throttle=5 2>&1)
    
    # Extract results
    FINAL=$(echo "$OUTPUT" | grep "Final Balance:" | awk '{print $NF}' | tr -d '$,')
    NET=$(echo "$OUTPUT" | grep "Net Profit:" | awk '{print $NF}' | tr -d '$,')
    DD=$(echo "$OUTPUT" | grep "Max Drawdown %:" | awk '{print $NF}' | tr -d '%')
    TRADES=$(echo "$OUTPUT" | grep "Total Trades:" | awk '{print $NF}')
    WR=$(echo "$OUTPUT" | grep "Win Rate:" | awk '{print $NF}' | tr -d '%')
    COMM=$(echo "$OUTPUT" | grep "Total Commission:" | awk '{print $NF}' | tr -d '$,')
    
    if [ -z "$FINAL" ] || [ "$FINAL" = "0" ]; then
        echo "  ERROR: Month $MONTH failed!" | tee -a "$LOGFILE"
        echo "$OUTPUT" >> "$LOGFILE"
        continue
    fi
    
    # Calculate return %
    RET_PCT=$(python3 -c "print(f'{(($FINAL - $BALANCE) / $BALANCE) * 100:+.1f}')")
    
    echo "  End: \$$(printf '%0.0f' $FINAL) (${RET_PCT}%) | DD: ${DD}% | Trades: $TRADES | Comm: \$$(printf '%0.0f' $COMM)" | tee -a "$LOGFILE"
    
    # Track worst DD
    WORSE=$(python3 -c "print('yes' if float('$DD') > float('$WORST_DD') else 'no')")
    if [ "$WORSE" = "yes" ]; then
        WORST_DD="$DD"
    fi
    TOTAL_TRADES=$((TOTAL_TRADES + TRADES))
    
    # Carry equity forward
    BALANCE="$FINAL"
    
    # Update progress file
    python3 -c "
import json
json.dump({
    'status': 'running',
    'type': 'monthly_chain',
    'current_month': '$MONTH',
    'equity': $FINAL,
    'worst_dd': $WORST_DD,
    'total_trades': $TOTAL_TRADES,
    'updated_at': '$(date -Iseconds)'
}, open('backtest_progress.json', 'w'), indent=2)
"
done

# Restore original balance
sed -i "s/^INITIAL_BALANCE = .*/INITIAL_BALANCE = 20000.0/" settings.py

echo "" | tee -a "$LOGFILE"
echo "═══════════════════════════════════════════════════" | tee -a "$LOGFILE"
echo "  FINAL: \$20,000 → \$$(printf '%0.0f' $BALANCE)" | tee -a "$LOGFILE"
TOTAL_RET=$(python3 -c "print(f'{(($BALANCE - 20000) / 20000) * 100:+.1f}')")
RAR=$(python3 -c "dd=$WORST_DD; print(f'{(($BALANCE - 20000) / 20000) * 100 / dd:.1f}') if dd > 0 else print('inf')")
echo "  Return: ${TOTAL_RET}% | Worst DD: ${WORST_DD}% | RAR: ${RAR}" | tee -a "$LOGFILE"
echo "  Total Trades: ${TOTAL_TRADES}" | tee -a "$LOGFILE"
echo "═══════════════════════════════════════════════════" | tee -a "$LOGFILE"

# Save completion to progress
python3 -c "
import json
json.dump({
    'status': 'completed',
    'type': 'monthly_chain',
    'final_equity': $BALANCE,
    'return_pct': $TOTAL_RET,
    'worst_dd': $WORST_DD,
    'rar': $RAR,
    'total_trades': $TOTAL_TRADES,
    'logfile': '$LOGFILE',
    'updated_at': '$(date -Iseconds)'
}, open('backtest_progress.json', 'w'), indent=2)
"

echo "Log saved: $LOGFILE"
