#!/bin/bash
set -uo pipefail

# Test safe configs WITH background LP competition to see realistic fee capture
# Johann's question: does competing LP eat all fees at wide AW?

cd "$(dirname "$0")/.."
FORGE=~/.foundry/bin/forge

echo "=== Fee Revenue with Background LP Competition ==="
echo "BG LP: 40 ETH/layer × 5 layers = 200 ETH competing liquidity"
echo "Attack pattern: buybias=10 (90% sells), 2000 trades"
echo ""

printf "%-8s %-6s %-8s %-6s %-12s %-12s %-10s\n" "AS%" "AW" "ticks" "safe" "WETH_fees" "KRK_fees" "avg_PnL"

run_config() {
    local as_pct=$1 aw=$2 runs=${3:-5}
    local as_val=$(python3 -c "print(int($as_pct * 1e16))")
    
    local total=0 profitable=0 sum_pnl=0 sum_weth=0 sum_krk=0
    
    for i in $(seq 1 $runs); do
        local seed=$RANDOM$RANDOM$RANDOM
        local output=$(CI_VALUE=0 \
            AS_VALUE=$as_val \
            AW_VALUE=$aw \
            DD_VALUE=500000000000000000 \
            BATCH_SEED=$seed \
            OPTIMIZER_CLASS=ConfigurableOptimizer \
            UNCAPPED_SWAPS=true \
            FUZZING_RUNS=1 \
            BUY_BIAS=10 \
            TRADES_PER_RUN=2000 \
            BG_LP_ETH_PER_LAYER=40000000000000000000 \
            $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)
            local weth_fees=$(tail -1 "$csv_file" | cut -d',' -f19)
            local krk_fees=$(tail -1 "$csv_file" | cut -d',' -f20)
            
            if [ -n "$init_eth" ] && [ -n "$final_eth" ]; then
                local result=$(python3 -c "
init=$init_eth; final=$final_eth
weth=${weth_fees:-0}; krk=${krk_fees:-0}
pnl = (final - init) / 1e18
weth_e = weth / 1e18
krk_i = int(krk / 1e18)
prof = 1 if pnl > 0 else 0
print(f'{prof} {pnl:.1f} {weth_e:.1f} {krk_i}')
" 2>/dev/null || echo "0 0.0 0.0 0")
                
                local is_prof=$(echo "$result" | cut -d' ' -f1)
                local pnl=$(echo "$result" | cut -d' ' -f2)
                local weth=$(echo "$result" | cut -d' ' -f3)
                local krk=$(echo "$result" | cut -d' ' -f4)
                
                profitable=$((profitable + is_prof))
                sum_pnl=$(python3 -c "print(round($sum_pnl + $pnl, 1))")
                sum_weth=$(python3 -c "print(round($sum_weth + $weth, 1))")
                sum_krk=$((sum_krk + krk))
            fi
            rm -f "$csv_file"
        fi
        total=$((total + 1))
    done
    
    local avg_pnl=$(python3 -c "print(round($sum_pnl / $total, 1))")
    local avg_weth=$(python3 -c "print(round($sum_weth / $total, 1))")
    local avg_krk=$((sum_krk / total))
    
    local safe_str="✅ 0/$total"
    if [ "$profitable" -gt 0 ]; then
        safe_str="❌ $profitable/$total"
    fi
    
    # Calculate tick spacing for display
    local ticks=$(python3 -c "print(200 + 34 * 20 * $aw // 100)")
    
    printf "%-8s %-6s %-8s %-6s %-12s %-12s %-10s\n" \
        "${as_pct}%" "$aw" "${ticks}t" "$safe_str" "${avg_weth}W" "${avg_krk}K" "${avg_pnl}"
}

# Safe configs from 2D frontier (AW ≤ 100)
echo "--- Frontier safe configs (no BG LP previously) ---"
run_config 30 100 5
run_config 35 100 5
run_config 10 100 5

# New extended configs (AW > 100) that were safe
echo ""
echo "--- Extended AW configs (safe from recent sweep) ---"
run_config 50 150 5
run_config 50 200 5
run_config 70 200 5

# Comparison: bull config
echo ""
echo "--- Bull config for reference ---"
run_config 100 20 5

echo ""
echo "=== Done ==="
