#!/bin/bash
# OPTION 2: Periodic Re-Optimization
# Each month: run a 4-variant mini-sweep, pick best RAR, apply to that month

cd /var/www/html/crpytotradingbot

MONTHS="202508 202509 202510 202511 202512 202601 202602"
BALANCE=20000.0
ORIGINAL_BALANCE=$BALANCE

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

echo "╔══════════════════════════════════════════════════════════╗" | tee "$RESULTS_FILE"
echo "║  OPTION 2: PERIODIC RE-OPTIMIZATION (MONTHLY SWEEP)     ║" | tee -a "$RESULTS_FILE"
echo "║  4 variants tested per month, best RAR applied           ║" | tee -a "$RESULTS_FILE"
echo "╚══════════════════════════════════════════════════════════╝" | 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

run_variant() {
    local MONTH="$1"
    local BAL="$2"
    local LOT="$3"
    local TARGET="$4"
    
    sed -i "s/^INITIAL_BALANCE = .*/INITIAL_BALANCE = ${BAL}/" settings.py
    sed -i "s/^LOT_SIZE = .*/LOT_SIZE = ${LOT}/" settings.py
    sed -i "s/^_REF_THREAD_PROFIT_TARGET = .*/_REF_THREAD_PROFIT_TARGET = ${TARGET}/" settings.py
    
    nice -n 15 python3 bot_runner.py --csv="$MONTH" --max-rows=0 --timeout=480 --throttle=2 > /dev/null 2>&1
    
    local RJSON
    RJSON=$(ls -t results/result_*.json | head -1)
    if [ -f "$RJSON" ]; then
        python3 -c "
import json, sys
d = json.load(open('${RJSON}'))
ret = d.get('return_pct', 0)
dd = d.get('max_dd_pct', 0.01)
rar = round(ret / dd, 1) if dd > 0 else 0
net = d.get('net_profit', 0)
trades = d.get('total_trades', 0)
pf = d.get('profit_factor', 0)
gp = d.get('gross_profit', 0)
gl = d.get('gross_loss', 0)
comm = d.get('commission', 0)
print(f'{rar}|{ret}|{dd}|{net}|{trades}|{pf}|${LOT}|${TARGET}|{gp}|{gl}|{comm}')
"
    else
        echo "0|0|0|0|0|0|${LOT}|${TARGET}|0|0|0"
    fi
}

for MONTH in $MONTHS; do
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" | tee -a "$RESULTS_FILE"
    echo "OPTIMIZING: $MONTH | Equity: \$$(printf '%.2f' $BALANCE)" | tee -a "$RESULTS_FILE"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" | tee -a "$RESULTS_FILE"
    
    BASE_LOT=$(python3 -c "print(round(max(0.001, min($BALANCE * 0.0000015, 15.0)), 3))")
    BASE_TARGET=$(python3 -c "print(round(max(1.0, $BALANCE * 0.00075), 2))")
    
    # 4 variants
    V1_LOT=$(python3 -c "print(round(max(0.001, $BASE_LOT * 0.5), 3))")
    V1_TGT=$(python3 -c "print(round(max(1.0, $BASE_TARGET * 0.67), 2))")
    V2_LOT=$BASE_LOT
    V2_TGT=$BASE_TARGET
    V3_LOT=$(python3 -c "print(round(max(0.001, $BASE_LOT * 1.5), 3))")
    V3_TGT=$BASE_TARGET
    V4_LOT=$BASE_LOT
    V4_TGT=$(python3 -c "print(round(max(1.0, $BASE_TARGET * 1.5), 2))")
    
    echo "  V1 (conservative): lot=$V1_LOT, target=\$$V1_TGT" | tee -a "$RESULTS_FILE"
    echo "  V2 (base scaled):  lot=$V2_LOT, target=\$$V2_TGT" | tee -a "$RESULTS_FILE"
    echo "  V3 (bigger lots):  lot=$V3_LOT, target=\$$V3_TGT" | tee -a "$RESULTS_FILE"
    echo "  V4 (higher exit):  lot=$V4_LOT, target=\$$V4_TGT" | tee -a "$RESULTS_FILE"
    
    # Run all 4 and capture results
    echo "  Running sweeps..." | tee -a "$RESULTS_FILE"
    R1=$(run_variant "$MONTH" "$BALANCE" "$V1_LOT" "$V1_TGT")
    R2=$(run_variant "$MONTH" "$BALANCE" "$V2_LOT" "$V2_TGT")
    R3=$(run_variant "$MONTH" "$BALANCE" "$V3_LOT" "$V3_TGT")
    R4=$(run_variant "$MONTH" "$BALANCE" "$V4_LOT" "$V4_TGT")
    
    # Parse and find best RAR
    BEST=$(python3 -c "
results = [
    ('V1_conservative', '''$R1'''),
    ('V2_base',         '''$R2'''),
    ('V3_big_lot',      '''$R3'''),
    ('V4_high_exit',    '''$R4'''),
]
best_rar = -999
best_label = ''
best_data = ''
for label, data in results:
    parts = data.strip().split('|')
    if len(parts) >= 8:
        rar = float(parts[0])
        ret = parts[1]
        dd = parts[2]
        print(f'  {label}: RAR={rar}, Return={ret}%, DD={dd}%')
        if rar > best_rar:
            best_rar = rar
            best_label = label
            best_data = data.strip()
    else:
        print(f'  {label}: FAILED ({data.strip()})')
# Output winner on last line with special prefix
print(f'WINNER|{best_label}|{best_data}')
")
    
    echo "$BEST" | grep -v "^WINNER" | tee -a "$RESULTS_FILE"
    
    # Extract winner line
    WINNER_LINE=$(echo "$BEST" | grep "^WINNER")
    W_LABEL=$(echo "$WINNER_LINE" | cut -d'|' -f2)
    W_RAR=$(echo "$WINNER_LINE" | cut -d'|' -f3)
    W_RET=$(echo "$WINNER_LINE" | cut -d'|' -f4)
    W_DD=$(echo "$WINNER_LINE" | cut -d'|' -f5)
    W_NET=$(echo "$WINNER_LINE" | cut -d'|' -f6)
    W_TRADES=$(echo "$WINNER_LINE" | cut -d'|' -f7)
    W_PF=$(echo "$WINNER_LINE" | cut -d'|' -f8)
    W_LOT=$(echo "$WINNER_LINE" | cut -d'|' -f9)
    W_TGT=$(echo "$WINNER_LINE" | cut -d'|' -f10)
    W_GP=$(echo "$WINNER_LINE" | cut -d'|' -f11)
    W_GL=$(echo "$WINNER_LINE" | cut -d'|' -f12)
    W_COMM=$(echo "$WINNER_LINE" | cut -d'|' -f13)
    
    echo "" | tee -a "$RESULTS_FILE"
    echo "  ★ WINNER: $W_LABEL (RAR=$W_RAR) → lot=$W_LOT, target=\$$W_TGT" | tee -a "$RESULTS_FILE"
    
    # The winner's result is already in the latest JSON — just use it
    # Update balance
    if [ -n "$W_NET" ] && [ "$W_NET" != "" ]; then
        NEW_BALANCE=$(python3 -c "print(round($BALANCE + float('$W_NET'), 2))")
        
        TOTAL_TRADES=$(python3 -c "print(int($TOTAL_TRADES + float('${W_TRADES:-0}')))")
        TOTAL_GROSS_PROFIT=$(python3 -c "print(round($TOTAL_GROSS_PROFIT + float('${W_GP:-0}'), 2))")
        TOTAL_GROSS_LOSS=$(python3 -c "print(round($TOTAL_GROSS_LOSS + float('${W_GL:-0}'), 2))")
        TOTAL_COMMISSION=$(python3 -c "print(round($TOTAL_COMMISSION + float('${W_COMM:-0}'), 2))")
        
        IS_WORSE=$(python3 -c "print(1 if float('${W_DD:-0}') > float('$OVERALL_MAX_DD_PCT') else 0)")
        if [ "$IS_WORSE" -eq 1 ]; then
            OVERALL_MAX_DD_PCT=$W_DD
        fi
        
        echo "  → $MONTH: \$$(printf '%.2f' $BALANCE) → \$$(printf '%.2f' $NEW_BALANCE) | Return: ${W_RET}% | DD: ${W_DD}%" | tee -a "$RESULTS_FILE"
        echo "" | tee -a "$RESULTS_FILE"
        BALANCE=$NEW_BALANCE
    else
        echo "  ERROR: Could not parse winner data" | tee -a "$RESULTS_FILE"
    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(float('$TOTAL_GROSS_LOSS')); print(round(float('$TOTAL_GROSS_PROFIT') / gl, 2) if gl > 0 else 'inf')")

echo "" | tee -a "$RESULTS_FILE"
echo "╔══════════════════════════════════════════════════════════════╗" | tee -a "$RESULTS_FILE"
echo "║  ADAPTIVE SWEEP 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"
