#!/usr/bin/env bash
# Template orchestrator for a SGLang vs vLLM benchmark experiment.
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 "max_model_len=${MAX_MODEL_LEN}"
log "scenarios=${#SCENARIOS[@]}"

# ---------------------------------------------------------------------------
# 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 backend="$1"
  local pid_file="/data/user1/yy/${EXPERIMENT_NAME}_${backend}.pid"
  if [[ -f "$pid_file" ]]; then
    local pid
    pid="$(cat "$pid_file")"
    if kill -0 "$pid" 2>/dev/null; then
      log "stopping ${backend} server pid=${pid}"
      kill "$pid" 2>/dev/null || true
      sleep 5
      kill -9 "$pid" 2>/dev/null || true
    fi
    rm -f "$pid_file"
  fi
  # Fallback cleanup.
  if [[ "$backend" == "sglang" ]]; then
    pkill -9 -f "sglang serve.*${MODEL_NAME}" 2>/dev/null || true
  else
    pkill -9 -f "vllm serve.*${MODEL_NAME}" 2>/dev/null || true
  fi
  sleep 2
}

start_server() {
  local backend="$1"
  local start_script
  if [[ "$backend" == "sglang" ]]; then
    start_script="${SGLANG_START_SCRIPT}"
    local port="$SGLANG_PORT"
  else
    start_script="${VLLM_START_SCRIPT}"
    local port="$VLLM_PORT"
  fi

  log "starting ${backend} server with ${start_script}"
  bash "${start_script}" >> "${log_dir_global}/${backend}.server.outer.log" 2>&1

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

run_warmup() {
  local backend="$1"
  local port
  if [[ "$backend" == "sglang" ]]; then
    port="$SGLANG_PORT"
  else
    port="$VLLM_PORT"
  fi

  log "warming up ${backend}"
  "${VENV_CLIENT}/bin/python" "${SCRIPT_DIR}/../../scripts/common/warmup.py" \
    --backend "$backend" \
    --port "$port" \
    --input-len 4000 \
    --output-len 512 \
    --num 2 \
    --env-python "${VENV_CLIENT}/bin/python" \
    >> "${log_dir_global}/${backend}.warmup.log" 2>&1
  log "warmup for ${backend} 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 backend="$1"
  local result_root="${RESULT_BASE}/${RUN_ID}/${backend}"
  local raw_dir="${result_root}/raw_outputs"
  local phase_log_dir="${result_root}/logs"

  mkdir -p "$raw_dir" "$phase_log_dir"

  local port
  if [[ "$backend" == "sglang" ]]; then
    port="$SGLANG_PORT"
  else
    port="$VLLM_PORT"
  fi

  log "===== ${backend} START (max_model_len=${MAX_MODEL_LEN}) ====="

  stop_server "$backend"
  start_server "$backend"
  run_warmup "$backend"

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

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

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

    "${VENV_CLIENT}/bin/python" -m sglang.bench_serving \
      --backend "$backend" \
      --host 127.0.0.1 \
      --port "$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: ${backend} scenario c=${concurrency} i=${input_len} o=${output_len} failed; see ${detail_log}"
        continue
      }

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

  stop_server "$backend"
  log "===== ${backend} DONE ====="
}

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

write_backend_metadata() {
  local backend="$1"
  local result_root="${RESULT_BASE}/${RUN_ID}/${backend}"
  ensure_result_root "$result_root"
  local meta_json="${result_root}/results.json"

  local env_path
  if [[ "$backend" == "sglang" ]]; then
    env_path="$VENV_SGLANG"
  else
    env_path="$VENV_VLLM"
  fi

  # Capture the exact server launch args for reproducibility.
  local server_args
  if [[ "$backend" == "sglang" ]]; then
    server_args="sglang serve --trust-remote-code --model-path $MODEL_PATH --tp $TP --moe-runner-backend marlin --context-length $MAX_MODEL_LEN --max-running-requests $MAX_RUNNING --mem-fraction-static 0.88 --host 0.0.0.0 --port $SGLANG_PORT"
  else
    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 --no-disable-hybrid-kv-cache-manager --disable-uvicorn-access-log --port $VLLM_PORT"
  fi

  write_metadata_json \
    "$meta_json" \
    "${EXPERIMENT_NAME}_${backend}" \
    "$RUN_ID" \
    "$MODEL_PATH" \
    "$backend" \
    "$backend" \
    "$HARDWARE" \
    "$ACCELERATOR" \
    "$CHIP" \
    "experiments/${EXPERIMENT_NAME}/run_bench.sh" \
    "$env_path" \
    "${HARDWARE} ${backend} TP=${TP} benchmark for ${MODEL_NAME}"

  jq --arg backend "$backend" \
     --arg server_args "$server_args" \
     '.config = {
        "tp": ($TP | tonumber),
        "cuda_visible_devices": $CUDA_VISIBLE_DEVICES,
        "max_model_len": ($MAX_MODEL_LEN | tonumber),
        "backend": $backend,
        "server_start_script": "experiments/\($EXPERIMENT_NAME)/start_\($backend).sh",
        "server_args": $server_args
      }' "$meta_json" > "${meta_json}.tmp" && mv "${meta_json}.tmp" "$meta_json"
}

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

stop_server sglang
stop_server vllm

write_backend_metadata sglang
write_backend_metadata vllm

run_benchmark sglang
parse_backend sglang

run_benchmark vllm
parse_backend vllm

log "generating comparison report"
"${VENV_CLIENT}/bin/python" "${SCRIPT_DIR}/../../scripts/common/compare.py" \
  --sglang "${RESULT_BASE}/${RUN_ID}/sglang" \
  --vllm "${RESULT_BASE}/${RUN_ID}/vllm" \
  --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}"
