#!/bin/bash
# Pre-flight: verify MultiConnector(Mooncake kv_both, LMCacheConnectorV1).
# Exits 42 if LMCache missing, 1 on crash, 0 on OK.
set -euo pipefail
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
RUN_DIR="${RUN_DIR:-$HERE/../results/preflight/multi}"
mkdir -p "$RUN_DIR"

PORT="${PORT:-8000}"

if ! "$(dirname "$HERE")/launch/launch_multi_mooncake_lmcache.sh"; then
    rc=$?
    if [[ $rc == 42 ]]; then
        echo "SKIP: lmcache missing" >&2
        exit 42
    fi
    echo "FAIL: launch failed with code $rc" >&2
    exit 1
fi

MODEL="$HOME/models/Qwen/$(ls $HOME/models/Qwen | grep Qwen3-Coder-30B | head -1)"

for i in 1 2 3 4 5; do
    code=$(curl -s -o "$RUN_DIR/req_$i.json" -w "%{http_code}" \
        -X POST "http://127.0.0.1:$PORT/v1/chat/completions" \
        -H 'Content-Type: application/json' \
        -d "{\"model\":\"$MODEL\",\"messages\":[{\"role\":\"user\",\"content\":\"multi $i\"}],\"max_tokens\":32,\"temperature\":0}" \
        --max-time 60 || echo "000")
    if [[ "$code" != "200" ]]; then
        echo "FAIL: req $i status=$code" >&2
        exit 1
    fi
done

echo "OK: MultiConnector reachable, all 5 requests succeeded"
