#!/bin/bash
# DD-ADAPTIVE RUN — TIER 1 WINNER CONFIG
# TTP=$8, RTP=$50, MO=15 with DD-adaptive lot/target scaling
# Compare against baseline DD-adaptive ($1.41M / $1.69M)

cd /var/www/html/crpytotradingbot

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

# Tier 1 winner base params
BASE_TTP=8.0
BASE_RTP=50.0
BASE_MO=15

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

echo "╔══════════════════════════════════════════════════════════╗" | tee "$RESULTS_FILE"
echo "║  DD-ADAPTIVE: TIER 1 WINNER CONFIG                      ║" | tee -a "$RESULTS_FILE"
echo "║  TTP=\$${BASE_TTP} | RTP=\$${BASE_RTP} | MO=${BASE_MO} | LOT=0.02 base  ║" | tee -a "$RESULTS_FILE"
echo "╚══════════════════════════════════════════════════════════╝" | tee -a "$RESULTS_FILE"

TOTAL_TRADES=0
TOTAL_COMMISSION=0
OVERALL_MAX_DD_PCT=0
PREV_DD=0

for MONTH in $MONTHS; do
    # Adjust scale based on previous month's DD
    SCALE=$(python3 -c "
prev_dd = $PREV_DD
scale = $SCALE
if prev_dd > 20:
    scale = max(0.25, scale * 0.25)
elif prev_dd > 10:
    scale = max(0.25, scale * 0.5)
elif prev_dd > 5:
    scale = scale
elif prev_dd > 0:
    scale = min(1.5, scale * 1.25)
print(round(scale, 3))
")

    # Scale lot and targets with equity
    NEW_LOT=$(python3 -c "
base_lot = $BALANCE * 0.000001 * $SCALE  # 0.02 at 20K
lot = round(max(0.001, min(base_lot, 15.0)), 3)
print(lot)
")
    NEW_TTP=$(python3 -c "
base_target = $BALANCE * 0.0004 * $SCALE  # $8 at 20K
target = round(max(1.0, base_target), 2)
print(target)
")
    NEW_RTP=$(python3 -c "
base_target = $BALANCE * 0.0025 * $SCALE  # $50 at 20K
target = round(max(5.0, base_target), 2)
print(target)
")

    echo "" | tee -a "$RESULTS_FILE"
    echo "━━ $MONTH | \$$(printf '%.0f' $BALANCE) | Scale: ${SCALE}x | Lot: ${NEW_LOT} | TTP: \$${NEW_TTP} | RTP: \$${NEW_RTP}" | tee -a "$RESULTS_FILE"

    sed -i "s/^INITIAL_BALANCE = .*/INITIAL_BALANCE = ${BALANCE}/" settings.py
    sed -i "s/^LOT_SIZE = .*/LOT_SIZE = ${NEW_LOT}/" settings.py
    sed -i "s/^THREAD_PROFIT_TARGET = .*/THREAD_PROFIT_TARGET = ${NEW_TTP}/" settings.py
    sed -i "s/^RECOVERY_PROFIT_TARGET = .*/RECOVERY_PROFIT_TARGET = ${NEW_RTP}/" settings.py
    sed -i "s/^MAX_INITIAL_ORDERS = .*/MAX_INITIAL_ORDERS = ${BASE_MO}/" settings.py

    OUTPUT=$(nice -n 15 python3 bot_runner.py --csv="$MONTH" --max-rows=0 --timeout=480 --throttle=2 2>&1)
    EXIT_CODE=$?

    if [ $EXIT_CODE -ne 0 ]; then
        echo "ERROR: Segment $MONTH failed (exit $EXIT_CODE)" | tee -a "$RESULTS_FILE"
        echo "$OUTPUT" | tail -10 | tee -a "$RESULTS_FILE"
        break
    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))")
        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 "print(round(($NEW_BALANCE - $BALANCE) / $BALANCE * 100, 1))")

        TOTAL_TRADES=$((TOTAL_TRADES + TRADES))
        TOTAL_COMMISSION=$(python3 -c "print($TOTAL_COMMISSION + $COMM)")

        IS_WORSE=$(python3 -c "print(1 if $DD > $OVERALL_MAX_DD_PCT else 0)")
        [ "$IS_WORSE" -eq 1 ] && OVERALL_MAX_DD_PCT=$DD
        PREV_DD=$DD

        echo "  → \$$(printf '%.0f' $NEW_BALANCE) (${RET}%) | DD: ${DD}% | Trades: $TRADES" | tee -a "$RESULTS_FILE"
        BALANCE=$NEW_BALANCE
    fi
done

# Restore settings
sed -i "s/^INITIAL_BALANCE = .*/INITIAL_BALANCE = 20000.0/" settings.py
sed -i "s/^LOT_SIZE = .*/LOT_SIZE = 0.02/" settings.py
sed -i "s/^THREAD_PROFIT_TARGET = .*/THREAD_PROFIT_TARGET = 15/" settings.py
sed -i "s/^RECOVERY_PROFIT_TARGET = .*/RECOVERY_PROFIT_TARGET = 30.0/" settings.py
sed -i "s/^MAX_INITIAL_ORDERS = .*/MAX_INITIAL_ORDERS = 10/" settings.py

TOTAL_RETURN=$(python3 -c "print(round(($BALANCE - $ORIGINAL_BALANCE) / $ORIGINAL_BALANCE * 100, 1))")
RAR=$(python3 -c "dd=$OVERALL_MAX_DD_PCT; print(round(($BALANCE - $ORIGINAL_BALANCE) / $ORIGINAL_BALANCE * 100 / dd, 1)) if dd > 0 else print('inf')")

echo "" | tee -a "$RESULTS_FILE"
echo "═══════════════════════════════════════════════════════════" | tee -a "$RESULTS_FILE"
echo "  TIER 1 DD-ADAPTIVE FINAL: \$20K → \$$(printf '%.0f' $BALANCE)" | tee -a "$RESULTS_FILE"
echo "  Return: ${TOTAL_RETURN}% | Worst DD: ${OVERALL_MAX_DD_PCT}% | RAR: ${RAR}" | tee -a "$RESULTS_FILE"
echo "  Trades: ${TOTAL_TRADES} | Commission: \$$(printf '%.0f' $TOTAL_COMMISSION)" | tee -a "$RESULTS_FILE"
echo "═══════════════════════════════════════════════════════════" | tee -a "$RESULTS_FILE"

# Write progress for bot_check.sh
python3 -c "
import json
json.dump({
    'status': 'completed',
    'type': 'adaptive_tier1',
    'final_equity': $BALANCE,
    'return_pct': $TOTAL_RETURN,
    'worst_dd': $OVERALL_MAX_DD_PCT,
    'rar': $RAR,
    'total_trades': $TOTAL_TRADES,
    'logfile': '$RESULTS_FILE',
    'updated_at': '$(date -Iseconds)'
}, open('backtest_progress.json', 'w'), indent=2)
"

echo "Done. Log: $RESULTS_FILE"
