#!/bin/bash
set -uo pipefail

# Sweep anchorShare at AW=100 (fixed safe clamp)
# Measure both safety AND fee revenue at each level
#
# Usage:
#   ./analysis/run-as-sweep.sh                    # Default: AS 10-100%, 5 runs, buybias=10
#   ./analysis/run-as-sweep.sh 40 100 10 5 10     # AS 40-100% step 10, 5 runs, buybias=10

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

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

AS_START=${1:-10}
AS_END=${2:-100}
AS_STEP=${3:-10}
RUNS=${4:-5}
BUYBIAS=${5:-10}

LOG="analysis/AS_SWEEP_LOG.md"
echo "# AnchorShare Sweep at AW=100 — $(date -u '+%Y-%m-%d %H:%M UTC')" > "$LOG"
echo "" >> "$LOG"
echo "CI=0, AW=100, DD=0.3e18. Only AS varies." >> "$LOG"
echo "AS range: ${AS_START}% to ${AS_END}% step ${AS_STEP}%, buybias=$BUYBIAS, runs=$RUNS" >> "$LOG"
echo "" >> "$LOG"

run_as_test() {
    local as_pct=$1
    local runs=$2
    local buybias=$3

    # Convert AS percentage to 1e18 scale
    local AS_VALUE=$(python3 -c "print(int($as_pct * 1e18 / 100))")

    echo "=== AS=${as_pct}% AW=100 buybias=$buybias ==="
    echo "### AS=${as_pct}% (buybias=$buybias)" >> "$LOG"

    local profitable=0
    local total=0
    local pnl_list=""
    local fee_weth_list=""
    local fee_krk_list=""

    for i in $(seq 1 $runs); do
        printf "  Run $i/$runs... "
        local seed=$RANDOM$RANDOM$RANDOM
        local output
        output=$(CI_VALUE=0 AS_VALUE=$AS_VALUE AW_VALUE=100 DD_VALUE=300000000000000000 \
            BATCH_SEED=$seed OPTIMIZER_CLASS=ConfigurableOptimizer \
            UNCAPPED_SWAPS=true FUZZING_RUNS=1 BUY_BIAS=$buybias \
            TRADES_PER_RUN=2000 BG_LP_ETH_PER_LAYER=0 \
            "$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
            # Extract PnL + fee data from CSV
            local result
            result=$(python3 -c "
import csv
rows = list(csv.reader(open('$csv_file')))
header = rows[0]
first = rows[1]
last = rows[-1]
cols = {h: i for i, h in enumerate(header)}

# eth_balance = trader WETH (column index 12)
eth_col = cols.get('eth_balance', 12)
init_eth = float(first[eth_col])
final_eth = float(last[eth_col])
pnl = (final_eth - init_eth) / 1e18

fee_weth = float(last[cols['fee_dest_weth']]) / 1e18 if 'fee_dest_weth' in cols else 0
fee_krk = float(last[cols['fee_dest_krk']]) / 1e18 if 'fee_dest_krk' in cols else 0

status = 'PROFIT' if pnl > 0 else 'SAFE'
print(f'{status} {pnl:.1f} {fee_weth:.1f} {fee_krk:.0f}')
" 2>/dev/null || echo "ERR 0 0 0")

            local status=$(echo "$result" | cut -d' ' -f1)
            local pnl=$(echo "$result" | cut -d' ' -f2)
            local fee_w=$(echo "$result" | cut -d' ' -f3)
            local fee_k=$(echo "$result" | cut -d' ' -f4)

            if [ "$status" = "ERR" ]; then
                echo "⚠️ parse error"
            elif [ "$status" = "PROFIT" ]; then
                profitable=$((profitable + 1))
                echo "❌ +${pnl} ETH | fees: ${fee_w} WETH, ${fee_k} KRK"
            else
                echo "✅ ${pnl} ETH | fees: ${fee_w} WETH, ${fee_k} KRK"
            fi

            pnl_list="$pnl_list $pnl"
            fee_weth_list="$fee_weth_list $fee_w"
            fee_krk_list="$fee_krk_list $fee_k"
            rm -f "$csv_file"
        else
            echo "⚠️ no CSV"
        fi
        total=$((total + 1))
    done

    # Compute averages
    local avg
    avg=$(python3 -c "
vals = [float(x) for x in '$pnl_list'.split() if x and x != '0']
fw = [float(x) for x in '$fee_weth_list'.split() if x and x != '0']
fk = [float(x) for x in '$fee_krk_list'.split() if x and x != '0']
if vals:
    print(f'{sum(vals)/len(vals):.1f} {sum(fw)/len(fw) if fw else 0:.1f} {sum(fk)/len(fk) if fk else 0:.0f}')
else:
    print('N/A N/A N/A')
" 2>/dev/null || echo "N/A N/A N/A")
    local avg_pnl=$(echo $avg | cut -d' ' -f1)
    local avg_fw=$(echo $avg | cut -d' ' -f2)
    local avg_fk=$(echo $avg | cut -d' ' -f3)

    local emoji="✅"; [ "$profitable" -gt 0 ] && emoji="❌"
    echo "$emoji AS=${as_pct}%: $profitable/$total profitable, avg PnL=${avg_pnl} ETH, fees: ${avg_fw} WETH + ${avg_fk} KRK"
    echo "| AS=${as_pct}% | **$profitable/$total** $emoji | avg PnL: ${avg_pnl} ETH | fees: ${avg_fw} WETH + ${avg_fk} KRK |" >> "$LOG"
    echo "" >> "$LOG"

    # Disk check
    local disk_pct=$(df / --output=pcent | tail -1 | tr -d ' %')
    [ "$disk_pct" -gt 85 ] && { echo "DISK FULL"; exit 1; }
}

echo "## Sell-Heavy Attack (buybias=$BUYBIAS)" >> "$LOG"
echo "" >> "$LOG"
echo "| Config | Safety | Avg PnL | Fees |" >> "$LOG"
echo "|--------|--------|---------|------|" >> "$LOG"

for as_val in $(seq $AS_START $AS_STEP $AS_END); do
    run_as_test $as_val $RUNS $BUYBIAS
done

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