#!/bin/bash
# OPTION 1: Equity-Scaled Rebalance
# Maintains constant lot_size/equity ratio across months
# Base ratio from winning config: 0.03 lots / $20,000 = 0.0000015
# Thread target ratio: $15 / $20,000 = 0.00075

cd /var/www/html/crpytotradingbot

MONTHS="202508 202509 202510 202511 202512 202601 202602"
BALANCE=20000.0
ORIGINAL_BALANCE=$BALANCE
BASE_LOT=0.03
BASE_TARGET=15.0
BASE_EQUITY=20000.0
LOT_RATIO=$(python3 -c "print($BASE_LOT / $BASE_EQUITY)")    # 0.0000015
TARGET_RATIO=$(python3 -c "print($BASE_TARGET / $BASE_EQUITY)")  # 0.00075

RESULTS_FILE="results/equity_scaled_$(date +%Y%m%d_%H%M%S).txt"
mkdir -p results

echo "╔══════════════════════════════════════════════════════════╗" | tee "$RESULTS_FILE"
echo "║  OPTION 1: EQUITY-SCALED REBALANCE                      ║" | tee -a "$RESULTS_FILE"
echo "║  Lot ratio: ${LOT_RATIO}/equity  Target ratio: ${TARGET_RATIO}/equity ║" | tee -a "$RESULTS_FILE"
echo "╚══════════════════════════════════════════════════════════╝" | tee -a "$RESULTS_FILE"
echo "Starting balance: \$${BALANCE}" | tee -a "$RESULTS_FILE"
echo "" | tee -a "$RESULTS_FILE"

TOTAL_TRADES=0
TOTAL_GROSS_PROFIT=0
TOTAL_GROSS_LOSS=0
TOTAL_COMMISSION=0
OVERALL_MAX_DD_PCT=0

for MONTH in $MONTHS; do
    # Scale lot size and thread target to current equity
    NEW_LOT=$(python3 -c "
lot = round($BALANCE * $LOT_RATIO, 3)
lot = max(0.001, min(lot, 15.0))  # clamp to settings bounds
# Round to lot_step=0.001
lot = round(lot, 3)
print(lot)
")
    NEW_TARGET=$(python3 -c "
target = round($BALANCE * $TARGET_RATIO, 2)
target = max(1.0, target)  # minimum $1
print(target)
")
    
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" | tee -a "$RESULTS_FILE"
    echo "SEGMENT: $MONTH | Balance: \$$(printf '%.2f' $BALANCE) | Lot: ${NEW_LOT} | Target: \$${NEW_TARGET}" | tee -a "$RESULTS_FILE"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" | tee -a "$RESULTS_FILE"
    
    # Update settings
    sed -i "s/^INITIAL_BALANCE = .*/INITIAL_BALANCE = ${BALANCE}/" settings.py
    sed -i "s/^LOT_SIZE = .*/LOT_SIZE = ${NEW_LOT}/" settings.py
    sed -i "s/^_REF_THREAD_PROFIT_TARGET = .*/_REF_THREAD_PROFIT_TARGET = ${NEW_TARGET}/" settings.py
    
    OUTPUT=$(nice -n 15 python3 bot_runner.py --csv="$MONTH" --max-rows=0 --timeout=480 --throttle=2 2>&1)
    EXIT_CODE=$?
    
    echo "$OUTPUT" | tee -a "$RESULTS_FILE"
    
    if [ $EXIT_CODE -ne 0 ]; then
        echo "ERROR: Segment $MONTH failed (exit $EXIT_CODE)" | tee -a "$RESULTS_FILE"
        # Restore settings
        sed -i "s/^INITIAL_BALANCE = .*/INITIAL_BALANCE = 20000.0/" settings.py
        sed -i "s/^LOT_SIZE = .*/LOT_SIZE = 0.03/" settings.py
        sed -i "s/^_REF_THREAD_PROFIT_TARGET = .*/_REF_THREAD_PROFIT_TARGET = 15.0/" settings.py
        exit 1
    fi
    
    RESULT_JSON=$(ls -t results/result_*.json | head -1)
    if [ -f "$RESULT_JSON" ]; then
        NEW_BALANCE=$(python3 -c "import json; d=json.load(open('$RESULT_JSON')); print(round($BALANCE + d.get('net_profit', 0), 2))")
        TRADES=$(python3 -c "import json; d=json.load(open('$RESULT_JSON')); print(d.get('total_trades', 0))")
        GP=$(python3 -c "import json; d=json.load(open('$RESULT_JSON')); print(d.get('gross_profit', 0))")
        GL=$(python3 -c "import json; d=json.load(open('$RESULT_JSON')); print(d.get('gross_loss', 0))")
        COMM=$(python3 -c "import json; d=json.load(open('$RESULT_JSON')); print(d.get('commission', 0))")
        DD=$(python3 -c "import json; d=json.load(open('$RESULT_JSON')); print(d.get('max_dd_pct', 0))")
        RET=$(python3 -c "import json; d=json.load(open('$RESULT_JSON')); print(d.get('return_pct', 0))")
        
        TOTAL_TRADES=$((TOTAL_TRADES + TRADES))
        TOTAL_GROSS_PROFIT=$(python3 -c "print($TOTAL_GROSS_PROFIT + $GP)")
        TOTAL_GROSS_LOSS=$(python3 -c "print($TOTAL_GROSS_LOSS + $GL)")
        TOTAL_COMMISSION=$(python3 -c "print($TOTAL_COMMISSION + $COMM)")
        
        IS_WORSE=$(python3 -c "print(1 if $DD > $OVERALL_MAX_DD_PCT else 0)")
        if [ "$IS_WORSE" -eq 1 ]; then
            OVERALL_MAX_DD_PCT=$DD
        fi
        
        echo "" | tee -a "$RESULTS_FILE"
        echo "→ $MONTH: \$$(printf '%.2f' $BALANCE) → \$$(printf '%.2f' $NEW_BALANCE) | Lot: ${NEW_LOT} | Return: ${RET}% | DD: ${DD}%" | tee -a "$RESULTS_FILE"
        echo "" | tee -a "$RESULTS_FILE"
        BALANCE=$NEW_BALANCE
    fi
done

# Restore original settings
sed -i "s/^INITIAL_BALANCE = .*/INITIAL_BALANCE = 20000.0/" settings.py
sed -i "s/^LOT_SIZE = .*/LOT_SIZE = 0.03/" settings.py
sed -i "s/^_REF_THREAD_PROFIT_TARGET = .*/_REF_THREAD_PROFIT_TARGET = 15.0/" settings.py

NET_PROFIT=$(python3 -c "print(round($BALANCE - $ORIGINAL_BALANCE, 2))")
TOTAL_RETURN=$(python3 -c "print(round(($BALANCE - $ORIGINAL_BALANCE) / $ORIGINAL_BALANCE * 100, 2))")
PF=$(python3 -c "gl=abs($TOTAL_GROSS_LOSS); print(round($TOTAL_GROSS_PROFIT / gl, 2) if gl > 0 else 'inf')")

echo "" | tee -a "$RESULTS_FILE"
echo "╔══════════════════════════════════════════════════════════════╗" | tee -a "$RESULTS_FILE"
echo "║  EQUITY-SCALED 6-MONTH RESULTS (Aug 2025 - Feb 2026)        ║" | tee -a "$RESULTS_FILE"
echo "╠══════════════════════════════════════════════════════════════╣" | tee -a "$RESULTS_FILE"
printf "║  Starting Balance:  \$%14.2f                              ║\n" $ORIGINAL_BALANCE | tee -a "$RESULTS_FILE"
printf "║  Final Balance:     \$%14.2f                              ║\n" $BALANCE | tee -a "$RESULTS_FILE"
printf "║  Net Profit:        \$%14.2f                              ║\n" $NET_PROFIT | tee -a "$RESULTS_FILE"
printf "║  Total Return:      %10s%%                                ║\n" $TOTAL_RETURN | tee -a "$RESULTS_FILE"
printf "║  Worst Segment DD:  %10s%%                                ║\n" $OVERALL_MAX_DD_PCT | tee -a "$RESULTS_FILE"
printf "║  Total Trades:      %10s                                  ║\n" $TOTAL_TRADES | tee -a "$RESULTS_FILE"
printf "║  Profit Factor:     %10s                                  ║\n" $PF | tee -a "$RESULTS_FILE"
printf "║  Total Commission:  \$%14.2f                              ║\n" $TOTAL_COMMISSION | tee -a "$RESULTS_FILE"
echo "╚══════════════════════════════════════════════════════════════╝" | tee -a "$RESULTS_FILE"
