#!/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/qwen3-eagle3-speed-bench-results}"
MODEL="${MODEL:-$ROOT_DIR/LLMs/Qwen3-4B-Q6_K.gguf}"
DRAFT_MODEL="${DRAFT_MODEL:-$ROOT_DIR/LLMs/Qwen3-4B-eagle3-bf16.gguf}"
PORT="${PORT:-8080}"
EAGLE3_N_MAX_VALUES="${EAGLE3_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=""
RSS_PID=""

stop_rss_logging() {
    if [[ -n "$RSS_PID" ]]; then
        kill "$RSS_PID" 2>/dev/null || true
        wait "$RSS_PID" 2>/dev/null || true
        RSS_PID=""
    fi
}

start_rss_logging() {
    local csv="$1"

    echo 'timestamp_utc,pid,rss_bytes' > "$csv" || return 1
    python3 - "$SERVER_PID" >> "$csv" <<'PYTHON' &
import datetime
import signal
import subprocess
import sys
import time

pid = sys.argv[1]

def stop(signum, frame):
    raise SystemExit(0)

signal.signal(signal.SIGTERM, stop)
signal.signal(signal.SIGINT, stop)
next_sample = time.monotonic()
while True:
    with subprocess.Popen(
        ["ps", "-o", "rss=", "-p", pid], stdout=subprocess.PIPE, text=True
    ) as process:
        output, _ = process.communicate()
    if process.returncode or not output.strip():
        break
    timestamp = datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="milliseconds")
    rss_bytes = int(output.strip()) * 1024
    print(f"{timestamp},{pid},{rss_bytes}", flush=True)
    next_sample += 0.1
    now = time.monotonic()
    if next_sample < now:
        next_sample = now
    time.sleep(next_sample - now)

PYTHON
    RSS_PID=$!
}

stop_server() {
    stop_rss_logging
    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,"cache_prompt":false}' \
        --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 [[ ! -f "$DRAFT_MODEL" ]]; then
    echo "Could not find draft model \"$DRAFT_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
trap 'exit 130' INT
trap 'exit 143' TERM

echo "Running Qwen3 Eagle3 SPEED-Bench sweep..."
echo "Model: $MODEL"
echo "Draft model: $DRAFT_MODEL"
echo "Server: $SERVER_EXE"
echo "Server args: $SERVER_ARGS"
echo "Eagle3 n_max values: $EAGLE3_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 'eagle3_n_max,bench,category,osl,concurrency,temperature,json,server_log,rss_csv' > "$RUN_INDEX"

read -r -a eagle3_n_max_values <<< "$EAGLE3_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 "${eagle3_n_max_values[@]}"; do
    SERVER_LOG="$RESULTS_DIR/server_eagle3_n${n_max}.log"
    draft_args=(--spec-draft-model "$DRAFT_MODEL" --spec-draft-ngl all)
    spec_type="draft-eagle3"
    if [[ "$n_max" == "0" ]]; then
        spec_type="none"
        draft_args=()
    fi

    echo "Starting llama-server with --spec-type $spec_type --spec-draft-n-max $n_max..."
    "$SERVER_EXE" \
        -m "$MODEL" \
        --port "$PORT" \
        "${server_args[@]}" \
        --cache-ram 0 \
        --no-cache-prompt \
        ${draft_args[@]+"${draft_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/eagle3_n${n_max}_${bench}_${category}_osl${osl}.json"
                RSS_CSV="${OUT_JSON%.json}_rss.csv"
                echo "Running bench=$bench category=$category osl=$osl n_max=$n_max..."

                start_rss_logging "$RSS_CSV" || fail $?
                run_speed_bench "$bench" "$category" "$osl" "$OUT_JSON" "$THROUGHPUT_LIMIT" || fail $?
                stop_rss_logging
                echo "$n_max,$bench,$category,$osl,1,0,\"$OUT_JSON\",\"$SERVER_LOG\",\"$RSS_CSV\"" >> "$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\"."
