#!/bin/bash
set -euo pipefail

# ---------------------------------------------------------------------------
# stop-hybrid-server.sh
# Stop the docling-fast hybrid FastAPI server using the stored PID file.
# ---------------------------------------------------------------------------

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PID_FILE="${SCRIPT_DIR}/hybrid-server.pid"

# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
info()  { echo "[INFO]  $*"; }
warn()  { echo "[WARN]  $*" >&2; }
error() { echo "[ERROR] $*" >&2; }

# ---------------------------------------------------------------------------
# 1. Read PID from file
# ---------------------------------------------------------------------------
if [[ ! -f "${PID_FILE}" ]]; then
    warn "PID file not found: ${PID_FILE}"
    warn "The server may not be running, or was started without this script."
    exit 1
fi

SERVER_PID="$(cat "${PID_FILE}")"

if [[ -z "${SERVER_PID}" ]]; then
    warn "PID file is empty: ${PID_FILE}"
    rm -f "${PID_FILE}"
    exit 1
fi

# ---------------------------------------------------------------------------
# 2. Check process existence
# ---------------------------------------------------------------------------
if ! kill -0 "${SERVER_PID}" 2>/dev/null; then
    warn "No process found with PID ${SERVER_PID}. It may have already exited."
    rm -f "${PID_FILE}"
    info "Removed stale PID file."
    exit 0
fi

# ---------------------------------------------------------------------------
# 3. Send SIGTERM and wait
# ---------------------------------------------------------------------------
info "Sending SIGTERM to PID ${SERVER_PID} …"
kill "${SERVER_PID}"

# Give the process up to 10 seconds to exit gracefully
WAIT=10
while (( WAIT > 0 )) && kill -0 "${SERVER_PID}" 2>/dev/null; do
    sleep 1
    (( WAIT-- )) || true
done

# ---------------------------------------------------------------------------
# 4. Force-kill if still alive
# ---------------------------------------------------------------------------
if kill -0 "${SERVER_PID}" 2>/dev/null; then
    warn "Process ${SERVER_PID} did not exit in time. Sending SIGKILL …"
    kill -9 "${SERVER_PID}" 2>/dev/null || true
fi

# ---------------------------------------------------------------------------
# 5. Remove PID file
# ---------------------------------------------------------------------------
rm -f "${PID_FILE}"
info "Hybrid server stopped (PID ${SERVER_PID}). PID file removed."
