#!/bin/bash

if [ -f ".env" ]; then
  set -a
  . ./.env
  set +a
fi

BASE_URL="http://127.0.0.1:8001/v1"
DEFAULT_MODEL_NAME="Qwen/Qwen3-32B"
MODEL_NAME="$DEFAULT_MODEL_NAME"

echo "🎙️ Avvio della Pipeline Audio Realtime (Porta 12345)..."
echo "💡 Premi Ctrl+C in questo terminale per fermarla."
echo "🔎 Query iniziale del modello in uso su ${BASE_URL}/models..."

DETECTED_MODEL_NAME=$(
  curl -fsS "${BASE_URL}/models" 2>/dev/null | ./venv/bin/python -c '
import json
import sys

data = json.load(sys.stdin)
models = data.get("data") or []
first = models[0] if models else {}
print(first.get("id", ""), end="")
' 2>/dev/null || true
)

if [ -n "$DETECTED_MODEL_NAME" ]; then
  MODEL_NAME="$DETECTED_MODEL_NAME"
  echo "🧠 Modello rilevato: $MODEL_NAME"
else
  echo "⚠️ Query fallita, uso il fallback configurato: $MODEL_NAME"
fi

echo "----------------------------------------------------"

PYTHONPATH=src ./venv/bin/python src/speech_to_speech/s2s_pipeline.py \
  --mode realtime \
  --ws_host 0.0.0.0 \
  --ws_port 12345 \
  --num_pipelines 2 \
  --llm_backend chat-completions \
  --qwen3_tts_backend torch \
  --model_name "$MODEL_NAME" \
  --responses_api_base_url "$BASE_URL" \
  --responses_api_api_key "EMPTY" \
  --qwen3_tts_model_name "Qwen/Qwen3-TTS-12Hz-1.7B-Base" \
  --qwen3_tts_ref_audio "female_short.wav" \
  --qwen3_tts_ref_text "Chile tiene uno de los acentos más reconocibles del mundo hispano y los generadores de español genérico no logran capturarlo."
