#!/usr/bin/env bash
# vLLM+MTP speculative decoding vs vLLM default comparison on H200.
# Reuses the default-side results from dsv4_h200_vllm_dspark_vs_default.
set -Eeuo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
EXPERIMENT_NAME="$(basename "$SCRIPT_DIR")"

# shellcheck source=/dev/null
source "${SCRIPT_DIR}/../../../scripts/common/lib.sh"
# shellcheck source=/dev/null
source "${SCRIPT_DIR}/../../../scripts/common/platform.sh"
# shellcheck source=/dev/null
source "${SCRIPT_DIR}/config.env"

RUN_ID="${RUN_ID:-$(date '+%Y%m%d-%H%M%S')}"
RESULT_BASE="${SCRIPT_DIR}/results"

log_dir_global="${RESULT_BASE}/${RUN_ID}/logs"
mkdir -p "$log_dir_global"
log_init "${log_dir_global}/orchestrator.log"

log "experiment=${EXPERIMENT_NAME}"
log "run_id=${RUN_ID}"
log "platform=${PLATFORM}"
log "hardware=${HARDWARE}"
log "model=${MODEL_PATH}"
log "spec_method=${SPEC_METHOD}"
log "spec_tokens=${SPEC_TOKENS}"
log "default_result_root=${DEFAULT_RESULT_ROOT}"

# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------

is_server_healthy() {
  local port="$1"
  curl --fail --silent --show-error --max-time 5 "http://127.0.0.1:${port}/health" >/dev/null 2>&1
}

stop_server() {
  local pid_file="/data/user1/yy/${EXPERIMENT_NAME}_mtp.pid"
  if [[ -f "$pid_file" ]]; then
    local pid
    pid="$(cat "$pid_file")"
    if kill -0 "$pid" 2>/dev/null; then
      log "stopping mtp server pid=${pid}"
      kill "$pid" 2>/dev/null || true
      sleep 5
      kill -9 "$pid" 2>/dev/null || true
    fi
    rm -f "$pid_file"
  fi
  pkill -9 -f "vllm serve.*DeepSeek-V4-Flash" 2>/dev/null || true
  sleep 2
}

start_server() {
  log "starting mtp server with ${MTP_START_SCRIPT}"
  bash "${MTP_START_SCRIPT}" >> "${log_dir_global}/mtp.server.outer.log" 2>&1

  if ! is_server_healthy "$MTP_PORT"; then
    log "error: mtp server failed to become healthy"
    return 1
  fi
  log "mtp server is healthy on port ${MTP_PORT}"
}

run_warmup() {
  log "warming up mtp (input=4000, output=512, num=2)"
  "${VENV_CLIENT}/bin/python" "${SCRIPT_DIR}/../../../scripts/common/warmup.py" \
    --backend vllm \
    --port "$MTP_PORT" \
    --input-len 4000 \
    --output-len 512 \
    --num 2 \
    --env-python "${VENV_CLIENT}/bin/python" \
    >> "${log_dir_global}/mtp.warmup.log" 2>&1
  log "warmup for mtp completed"
}

scenario_already_completed() {
  local output_file="$1"
  local expected="$2"
  [[ -s "$output_file" ]] || return 1
  local completed
  completed="$(${VENV_CLIENT}/bin/python -c "
import json, sys
path = sys.argv[1]
try:
    with open(path, 'r', encoding='utf-8') as f:
        for line in f:
            line = line.strip()
            if line:
                data = json.loads(line)
                print(data.get('completed', 0))
                break
except Exception:
    print(0)
" "$output_file")"
  [[ "${completed:-0}" -ge "$expected" ]]
}

run_benchmark() {
  local result_root="${RESULT_BASE}/${RUN_ID}/mtp"
  local raw_dir="${result_root}/raw_outputs"
  local bench_log_dir="${result_root}/logs"

  mkdir -p "$raw_dir" "$bench_log_dir"

  log "===== mtp BENCHMARK START ====="

  stop_server
  start_server
  run_warmup

  for scenario in "${SCENARIOS[@]}"; do
    read -r concurrency input_len output_len num_prompts <<< "$scenario"
    output_file="${raw_dir}/vllm_mtp_$(date '+%m%d')_${concurrency}_${input_len}_${output_len}.jsonl"
    detail_log="${bench_log_dir}/vllm_mtp_c${concurrency}_i${input_len}_o${output_len}.log"

    if scenario_already_completed "$output_file" "$num_prompts"; then
      log "skipping already-completed mtp scenario: c=${concurrency} i=${input_len} o=${output_len}"
      continue
    fi

    log "running mtp scenario: c=${concurrency} i=${input_len} o=${output_len} n=${num_prompts}"

    "${VENV_CLIENT}/bin/python" -m sglang.bench_serving \
      --backend vllm \
      --host 127.0.0.1 \
      --port "$MTP_PORT" \
      --dataset-name random \
      --random-input-len "$input_len" \
      --random-output-len "$output_len" \
      --num-prompts "$num_prompts" \
      --max-concurrency "$concurrency" \
      --request-rate 10000 \
      --output-file "$output_file" \
      --output-details \
      > "$detail_log" 2>&1 || {
        log "ERROR: mtp scenario c=${concurrency} i=${input_len} o=${output_len} failed; see ${detail_log}"
        continue
      }

    log "finished mtp scenario: output=${output_file}"
  done

  stop_server
  log "===== mtp BENCHMARK DONE ====="
}

parse_mtp() {
  local result_root="${RESULT_BASE}/${RUN_ID}/mtp"
  log "parsing mtp results in ${result_root}"
  "${VENV_CLIENT}/bin/python" "${SCRIPT_DIR}/../../../scripts/common/parse_backend.py" "$result_root" --backend vllm \
    >> "${result_root}/logs/parse.log" 2>&1 || {
      log "WARNING: parser failed for mtp; see ${result_root}/logs/parse.log"
    }
}

write_mtp_metadata() {
  local result_root="${RESULT_BASE}/${RUN_ID}/mtp"
  ensure_result_root "$result_root"
  local meta_json="${result_root}/results.json"

  local server_args
  server_args="vllm serve $MODEL_PATH --trust-remote-code --tensor-parallel-size $TP --kv-cache-dtype fp8 --max-model-len $MAX_MODEL_LEN --max-num-seqs $MAX_NUM_SEQS --block-size 256 --gpu-memory-utilization 0.90 --tokenizer-mode deepseek_v4 --reasoning-parser deepseek_v4 --speculative-config {\\\"method\\\":\\\"mtp\\\",\\\"num_speculative_tokens\\\":$SPEC_TOKENS} --no-disable-hybrid-kv-cache-manager --disable-uvicorn-access-log --port $MTP_PORT"

  write_metadata_json \
    "$meta_json" \
    "${EXPERIMENT_NAME}_mtp" \
    "$RUN_ID" \
    "$MODEL_PATH" \
    "vllm" \
    "vllm-mtp" \
    "$HARDWARE" \
    "$ACCELERATOR" \
    "$CHIP" \
    "experiments/${EXPERIMENT_NAME}/run_bench.sh" \
    "$VENV_VLLM" \
    "H200 vLLM+MTP TP=8 benchmark for DeepSeek-V4-Flash"

  jq --arg server_args "$server_args" \
     '.config = {
        "tp": 8,
        "cuda_visible_devices": "0,1,2,3,4,5,6,7",
        "max_model_len": 32768,
        "max_num_seqs": 256,
        "spec_method": "mtp",
        "spec_tokens": 1,
        "backend": "vllm",
        "server_start_script": "experiments/dsv4_h200_vllm_mtp_vs_default/start_mtp.sh",
        "server_args": $server_args
      }' "$meta_json" > "${meta_json}.tmp" && mv "${meta_json}.tmp" "$meta_json"
}

# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------

stop_server
write_mtp_metadata
run_benchmark
parse_mtp

log "generating comparison report"
"${VENV_CLIENT}/bin/python" "${SCRIPT_DIR}/compare.py" \
  --mtp "${RESULT_BASE}/${RUN_ID}/mtp" \
  --default "$DEFAULT_RESULT_ROOT" \
  --output "${RESULT_BASE}/${RUN_ID}/comparison.md" \
  >> "${log_dir_global}/compare.log" 2>&1 || {
    log "WARNING: comparison script failed; see ${log_dir_global}/compare.log"
  }

log "all results saved to ${RESULT_BASE}/${RUN_ID}"
