#!/bin/bash
set -e
clear

echo "==============================================="
echo "AI Voice Bridge 3.1 Whisper"
echo "macOS Launcher"
echo "==============================================="
echo

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

PORT="5055"
BRIDGE_HEALTH="$(curl -fsS --max-time 1 "http://127.0.0.1:${PORT}/health" 2>/dev/null || true)"

if echo "$BRIDGE_HEALTH" | grep -q '"service": "AI Voice Bridge"'; then
  RUNNING_VERSION="$(printf '%s' "$BRIDGE_HEALTH" | sed -n 's/.*"version": "\([^"]*\)".*/\1/p')"
  echo "[ALREADY RUNNING] AI Voice Bridge is already running on port ${PORT}."
  if [ -n "$RUNNING_VERSION" ]; then
    echo "Running version: $RUNNING_VERSION"
  fi
  echo
  echo "You do not need to start another server window."
  echo "Keep the existing AI Voice Bridge Terminal window open and use Chrome normally."
  echo
  read -n 1 -s -r -p "Press any key to exit this duplicate launcher..."
  exit 0
fi

EXISTING_PIDS="$(lsof -tiTCP:${PORT} -sTCP:LISTEN -n -P 2>/dev/null || true)"
if [ -n "$EXISTING_PIDS" ]; then
  echo "[PORT IN USE] Something is already listening on port ${PORT}."
  echo "AI Voice Bridge cannot start a second server on the same port."
  echo
  for PID in $EXISTING_PIDS; do
    CMD="$(ps -p "$PID" -o command= 2>/dev/null || true)"
    echo "PID $PID: $CMD"
  done
  echo
  echo "Close the existing app/server using port ${PORT}, then run this launcher again."
  echo "Advanced cleanup command: lsof -ti tcp:${PORT} | xargs kill -9"
  echo
  read -n 1 -s -r -p "Press any key to exit this launcher..."
  exit 1
fi

VENV_PYTHON="$SCRIPT_DIR/.venv/bin/python"
PYTHON_CMD=""

if [ -x "$VENV_PYTHON" ]; then
  PYTHON_CMD="$VENV_PYTHON"
elif command -v python3 >/dev/null 2>&1; then
  PYTHON_CMD="python3"
elif command -v python >/dev/null 2>&1 && python -c 'import sys; sys.exit(0 if sys.version_info[0] == 3 else 1)' >/dev/null 2>&1; then
  PYTHON_CMD="python"
fi

if [ -z "$PYTHON_CMD" ]; then
  echo "[MISSING] Python 3 was not detected."
  echo "Run the included python-3.10.11-macos11.pkg from this folder, then run this launcher again."
  read -n 1 -s -r -p "Press any key to exit this launcher..."
  exit 1
fi

echo "[OK] Python detected: $PYTHON_CMD"
echo
echo "Starting AI Voice Bridge 3.1 Whisper..."
echo "Server: http://127.0.0.1:5055"
echo "TTS output: macOS say"
echo "Dictation backend: Whisper / faster-whisper
Dictation: click the Mic button, or use Cmd+Shift+V
Readback: green Repeat replays the latest response, red Stop stops speech"
echo "If server says dictation unavailable, run Setup-Local-Dictation-Mac.command first."
echo "Stop spoken AI output: Esc"
echo
echo "Keep this window open while using AI Voice Bridge."
echo

"$PYTHON_CMD" "$SCRIPT_DIR/ai_voice_bridge_server.py" --port 5055

echo
echo "Server stopped."
read -n 1 -s -r -p "Press any key to exit this launcher..."
