#!/bin/bash
set -uo pipefail

# Test the V3 binary step output params
# V3 now uses direct 2D mapping with no intermediate score:
#   staked <= 91% → BEAR (AS=30%, AW=100, DD=0.3e18)
#   staked > 91% + low tax → BULL (AS=100%, AW=20, DD=1e18)
#
# BUGS FIXED from previous version:
#   1. Bear AS was 1e17 (10%) — should be 3e17 (30%) matching V3 contract
#   2. Had ramp transition 140-160 — V3 uses binary step, no intermediate params
#   3. DD was proportional to score — now binary (0.3e18 bear, 1e18 bull)

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
cd "$SCRIPT_DIR/.."

FORGE="${HOME}/.foundry/bin/forge"

LOG="analysis/V3_STEP_LOG.md"
echo "# OptimizerV3 Binary Step Test — $(date -u '+%Y-%m-%d %H:%M UTC')" > "$LOG"
echo "" >> "$LOG"
echo "V3 outputs exactly two configs (no intermediates):" >> "$LOG"
echo "- Bear: AS=30% AW=100 DD=0.3e18" >> "$LOG"
echo "- Bull: AS=100% AW=20 DD=1e18" >> "$LOG"
echo "" >> "$LOG"

check_resources() {
    local disk_pct=$(df / --output=pcent | tail -1 | tr -d ' %')
    if [ "$disk_pct" -gt 85 ]; then
        echo "DISK FULL ($disk_pct%) — stopping"
        exit 1
    fi
}

run_config() {
    local name=$1 config=$2 buybias=$3 runs=$4

    local CI=0
    local AS AW DD desc
    if [ "$config" = "bear" ]; then
        AS=300000000000000000   # 30% = 3e17
        AW=100
        DD=300000000000000000   # 0.3e18
        desc="AS=30% AW=100"
    elif [ "$config" = "bull" ]; then
        AS=1000000000000000000  # 100% = 1e18
        AW=20
        DD=1000000000000000000  # 1e18
        desc="AS=100% AW=20"
    else
        echo "Unknown config: $config"
        return 1
    fi

    echo "=== $name ($desc) buybias=$buybias ==="
    echo "### $name ($desc, buybias=$buybias)" >> "$LOG"

    local profitable=0
    local total=0
    for i in $(seq 1 $runs); do
        printf "  Run $i/$runs... "
        local seed=$RANDOM$RANDOM$RANDOM
        local output
        output=$(CI_VALUE=$CI AS_VALUE=$AS AW_VALUE=$AW DD_VALUE=$DD \
            BATCH_SEED=$seed OPTIMIZER_CLASS=ConfigurableOptimizer \
            UNCAPPED_SWAPS=true FUZZING_RUNS=1 BUY_BIAS=$buybias \
            TRADES_PER_RUN=2000 \
            "$FORGE" script analysis/StreamlinedFuzzing.s.sol:StreamlinedFuzzing \
                --skip-simulation --gas-estimate-multiplier 300 -vv 2>&1)

        local csv_prefix=$(echo "$output" | grep "prefix:" | sed 's/.*prefix: //')
        local csv_file="analysis/fuzz-${csv_prefix}-000.csv"

        if [ -f "$csv_file" ]; then
            local init_eth=$(head -2 "$csv_file" | tail -1 | cut -d',' -f13)
            local final_eth=$(tail -1 "$csv_file" | cut -d',' -f13)
            if [ -n "$init_eth" ] && [ -n "$final_eth" ]; then
                local pnl_eth
                pnl_eth=$(python3 -c "
init=$init_eth; final=$final_eth
pnl = (final - init) / 1e18
status = 'PROFIT' if pnl > 0 else 'SAFE'
print(f'{status} {pnl:.1f}')
" 2>/dev/null || echo "SAFE 0.0")
                local status=$(echo "$pnl_eth" | cut -d' ' -f1)
                local pnl=$(echo "$pnl_eth" | cut -d' ' -f2)
                if [ "$status" = "PROFIT" ]; then
                    profitable=$((profitable + 1))
                    echo "❌ +${pnl} ETH"
                else
                    echo "✅ ${pnl} ETH"
                fi
            fi
            rm -f "$csv_file"
        else
            echo "⚠️ no CSV"
        fi
        total=$((total + 1))
    done

    local emoji="✅"; [ "$profitable" -gt 0 ] && emoji="❌"
    echo "$emoji $profitable/$total profitable"
    echo "Result: **$profitable/$total** $emoji" >> "$LOG"
    echo "" >> "$LOG"
    check_resources
}

echo "Testing V3 binary step output configs..."
echo ""

# Bear config: AS=30% AW=100 — this is what V3 outputs for staked <= 91%
echo "## Bear Config (AS=30% AW=100)" >> "$LOG"
echo "" >> "$LOG"

run_config "bear-sellheavy" bear 10 5
run_config "bear-balanced"  bear 50 5

# Bull config: AS=100% AW=20 — this is what V3 outputs for euphoric staking
echo "## Bull Config (AS=100% AW=20)" >> "$LOG"
echo "" >> "$LOG"

run_config "bull-sellheavy" bull 10 5
run_config "bull-balanced"  bull 50 5

echo "" >> "$LOG"
echo "### Complete: $(date -u '+%Y-%m-%d %H:%M UTC')" >> "$LOG"
echo ""
echo "=== DONE ==="
echo "Results: analysis/V3_STEP_LOG.md"
