#!/bin/bash
# Run both Gradio demo and Realtime ASR server
#
# Usage:
#   ./run_all.sh
#
# Ports:
#   - 7860: Gradio UI (batch ASR)
#   - 8000: WebSocket API (realtime ASR)

set -e

cd "$(dirname "$0")"

# Configuration
GRADIO_HOST="${GRADIO_HOST:-0.0.0.0}"
GRADIO_PORT="${GRADIO_PORT:-7860}"
REALTIME_HOST="${REALTIME_HOST:-0.0.0.0}"
REALTIME_PORT="${REALTIME_PORT:-8000}"
MODEL_PATH="${VIBEVOICE_MODEL_PATH:-microsoft/VibeVoice-ASR}"

echo "=========================================="
echo "VibeVoice ASR - All Services"
echo "=========================================="
echo ""
echo "Starting services:"
echo "  - Gradio UI:      http://$GRADIO_HOST:$GRADIO_PORT"
echo "  - Realtime ASR:   http://$REALTIME_HOST:$REALTIME_PORT"
echo "  - Test Client:    http://$REALTIME_HOST:$REALTIME_PORT/static/realtime_client.html"
echo ""
echo "Model: $MODEL_PATH"
echo "=========================================="
echo ""

# Trap to clean up background processes on exit
cleanup() {
    echo ""
    echo "Shutting down..."
    kill $REALTIME_PID 2>/dev/null || true
    kill $GRADIO_PID 2>/dev/null || true
    wait
    echo "All services stopped."
}
trap cleanup EXIT INT TERM

# Start Realtime ASR server in background
echo "[1/2] Starting Realtime ASR server..."
python -m realtime.server \
    --host "$REALTIME_HOST" \
    --port "$REALTIME_PORT" \
    --model-path "$MODEL_PATH" \
    --no-preload &
REALTIME_PID=$!

# Wait a moment for the server to initialize
sleep 2

# Start Gradio demo in background
echo "[2/2] Starting Gradio demo..."
python demo/vibevoice_asr_gradio_demo.py \
    --host "$GRADIO_HOST" \
    --port "$GRADIO_PORT" \
    --model_path "$MODEL_PATH" &
GRADIO_PID=$!

echo ""
echo "Both services started. Press Ctrl+C to stop."
echo ""

# Wait for either process to exit
wait -n $REALTIME_PID $GRADIO_PID

# If one exits, the trap will clean up the other
