#!/usr/bin/env bash

set -uo pipefail

ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd) || exit 1
cd -- "$ROOT_DIR" || exit 1

VENV_ACTIVATE="${VENV_ACTIVATE:-$HOME/python-projects/llama.cpp-benchmarks/.venv/bin/activate}"
SERVER_EXE="${SERVER_EXE:-$ROOT_DIR/build-ninja-arm64-metal-release/bin/llama-server}"
SPEED_BENCH="${SPEED_BENCH:-tools/server/bench/speed-bench/speed_bench.py}"
RESULTS_DIR="${RESULTS_DIR:-results/mtp-speed-bench-results}"
MODEL="${MODEL:-$ROOT_DIR/LLMs/DeepSeek-V4-Pro-Qwen3.5-4B-MTP-Q6_K.gguf}"
PORT="${PORT:-8080}"
MTP_N_MAX_VALUES="${MTP_N_MAX_VALUES:-0 1 2 3 4 5}"
BENCH_VALUES="throughput_1k throughput_2k"
THROUGHPUT_CATEGORY_VALUES="${THROUGHPUT_CATEGORY_VALUES:-low_entropy high_entropy}"
OSL_VALUES="${OSL_VALUES:-1024 2048 4096}"
THROUGHPUT_LIMIT="${THROUGHPUT_LIMIT:-30}"
SERVER_ARGS="${SERVER_ARGS:--c 8192 -b 2048 -ub 2048 -ngl -1 -fa on --parallel 1 --jinja}"

RUN_INDEX="$RESULTS_DIR/runs.csv"
URL="localhost:$PORT"
SERVER_PID=""
SERVER_LOG=""
OUT_JSON=""

stop_server() {
    if [[ -n "$SERVER_PID" ]] && kill -0 "$SERVER_PID" 2>/dev/null; then
        kill "$SERVER_PID" 2>/dev/null || true

        for _ in {1..20}; do
            if ! kill -0 "$SERVER_PID" 2>/dev/null; then
                break
            fi
            sleep 0.1
        done

        if kill -0 "$SERVER_PID" 2>/dev/null; then
            kill -KILL "$SERVER_PID" 2>/dev/null || true
        fi
        wait "$SERVER_PID" 2>/dev/null || true
    fi

    SERVER_PID=""
    sleep 2
}

cleanup() {
    stop_server
}

fail() {
    local status="${1:-1}"

    stop_server
    echo "Benchmark failed with exit code $status."
    echo "Last output JSON: \"$OUT_JSON\""
    echo "Server log: \"$SERVER_LOG\""
    exit "$status"
}

wait_for_server() {
    local attempt

    for attempt in {1..60}; do
        if curl -fsS "http://$URL/health" >/dev/null 2>&1; then
            return 0
        fi

        if ! kill -0 "$SERVER_PID" 2>/dev/null; then
            echo "llama-server exited before becoming healthy. See \"$SERVER_LOG\"."
            return 1
        fi
        sleep 1
    done

    echo "llama-server did not become healthy. See \"$SERVER_LOG\"."
    return 1
}

activate_venv() {
    if [[ ! -f "$VENV_ACTIVATE" ]]; then
        echo "Could not find virtual environment activation script \"$VENV_ACTIVATE\"."
        return 1
    fi

    # shellcheck source=/dev/null
    source "$VENV_ACTIVATE"
}

run_speed_bench() {
    local bench="$1"
    local category="$2"
    local osl="$3"
    local out_json="$4"
    local run_limit="$5"
    local -a limit_args=()

    if [[ -n "$run_limit" ]]; then
        limit_args=(--limit "$run_limit")
    fi

    if ! activate_venv; then
        echo "Failed to activate Python virtual environment \"$VENV_ACTIVATE\"."
        return 1
    fi

    python "$SPEED_BENCH" \
        --url "$URL" \
        --bench "$bench" \
        --category "$category" \
        --osl "$osl" \
        --concurrency 1 \
        ${limit_args[@]+"${limit_args[@]}"}  \
        --extra-inputs '{"temperature":0}' \
        --output "$out_json"
}

if [[ -z "$MODEL" ]]; then
    echo "Set MODEL near the top of $(basename "$0") before running."
    echo "Example:"
    echo '  MODEL=/path/to/model.gguf'
    echo
    echo "Optional environment overrides:"
    echo "  SERVER_EXE=$SERVER_EXE"
    echo "  SERVER_ARGS=$SERVER_ARGS"
    echo "  PORT=$PORT"
    echo "  RESULTS_DIR=$RESULTS_DIR"
    echo "  THROUGHPUT_LIMIT=$THROUGHPUT_LIMIT"
    exit 1
fi

if [[ ! -f "$MODEL" ]]; then
    echo "Could not find model \"$MODEL\"."
    exit 1
fi

if [[ ! -x "$SERVER_EXE" ]]; then
    echo "Could not find executable \"$SERVER_EXE\"."
    exit 1
fi

if [[ ! -f "$SPEED_BENCH" ]]; then
    echo "Could not find \"$SPEED_BENCH\"."
    exit 1
fi

trap cleanup EXIT INT TERM

echo "Running MTP SPEED-Bench sweep..."
echo "Model: $MODEL"
echo "Server: $SERVER_EXE"
echo "Server args: $SERVER_ARGS"
echo "MTP n_max values: $MTP_N_MAX_VALUES"
echo "Benches: $BENCH_VALUES"
echo "Throughput categories: $THROUGHPUT_CATEGORY_VALUES"
echo "OSL values: $OSL_VALUES"
echo "Throughput sample limit per category: $THROUGHPUT_LIMIT"
echo "Results directory: $RESULTS_DIR"
echo

mkdir -p "$RESULTS_DIR"
echo 'mtp_n_max,bench,category,osl,concurrency,temperature,json,server_log' > "$RUN_INDEX"

read -r -a mtp_n_max_values <<< "$MTP_N_MAX_VALUES"
read -r -a bench_values <<< "$BENCH_VALUES"
read -r -a throughput_category_values <<< "$THROUGHPUT_CATEGORY_VALUES"
read -r -a osl_values <<< "$OSL_VALUES"
read -r -a server_args <<< "$SERVER_ARGS"

for n_max in "${mtp_n_max_values[@]}"; do
    SERVER_LOG="$RESULTS_DIR/server_mtp_n${n_max}.log"
    spec_type="draft-mtp"
    if [[ "$n_max" == "0" ]]; then
        spec_type="none"
    fi

    echo "Starting llama-server with --spec-type $spec_type --spec-draft-n-max $n_max..."
    "$SERVER_EXE" \
        -m "$MODEL" \
        --port "$PORT" \
        "${server_args[@]}" \
        --spec-type "$spec_type" \
        --spec-draft-n-max "$n_max" \
        > "$SERVER_LOG" 2>&1 &
    SERVER_PID=$!

    wait_for_server || fail $?

    for bench in "${bench_values[@]}"; do
        for category in "${throughput_category_values[@]}"; do
            for osl in "${osl_values[@]}"; do
                OUT_JSON="$RESULTS_DIR/mtp_n${n_max}_${bench}_${category}_osl${osl}.json"
                echo "Running bench=$bench category=$category osl=$osl n_max=$n_max..."

                run_speed_bench "$bench" "$category" "$osl" "$OUT_JSON" "$THROUGHPUT_LIMIT" || fail $?
                echo "$n_max,$bench,$category,$osl,1,0,\"$OUT_JSON\",\"$SERVER_LOG\"" >> "$RUN_INDEX"
            done
        done
    done

    stop_server
    echo "Finished n_max $n_max."
    echo
done

trap - EXIT INT TERM
echo "All benchmarks complete."
echo "Run index written to \"$RUN_INDEX\"."
echo "JSON outputs written to \"$RESULTS_DIR\"."
