#!/usr/bin/env bash
set -euo pipefail

# ============================================================
# photo_sanad.sh
# ------------------------------------------------------------
# ONE command to run everything:
#   ./photo_sanad.sh
#
# What it does:
# 1) Activates teleimager (py3.10) and starts teleimager image_server (--rs) in background
# 2) Activates gemini (py3.11) and runs /home/unitree/photographer/sanad_voice.py in foreground
# 3) Sets PulseAudio default sink/source (optional)
# 4) Sets PYTHONPATH for unitree_sdk2_python (so unitree_sdk2py imports work)
# 5) On exit, stops teleimager server
# ============================================================

BASE_DIR="/home/unitree/photographer"
PY_FILE="$BASE_DIR/voice_sanad.py"

# conda
CONDA_SH="/home/unitree/miniconda3/etc/profile.d/conda.sh"
ENV_TELE="teleimager"   # Python 3.10
ENV_GEM="gemini"        # Python 3.11

# Optional: choose your camera (if needed)
# export CAMERA_DEVICE=/dev/video2
# export PHOTO_PREFIX=photo
export CAMERA_DEVICE="${CAMERA_DEVICE:-/dev/video0}"
export PHOTO_PREFIX="${PHOTO_PREFIX:-photo}"

# PulseAudio device names (change if needed)
SINK="${SINK:-alsa_output.usb-Anker_PowerConf_A3321-DEV-SN1-01.analog-stereo}"
SOURCE="${SOURCE:-alsa_input.usb-Anker_PowerConf_A3321-DEV-SN1-01.mono-fallback}"

# ALSA plugin fix (helps conda envs stop spamming ALSA errors)
if [[ -d "/usr/lib/aarch64-linux-gnu/alsa-lib" ]]; then
  export ALSA_PLUGIN_DIR="/usr/lib/aarch64-linux-gnu/alsa-lib"
elif [[ -d "/usr/lib/alsa-lib" ]]; then
  export ALSA_PLUGIN_DIR="/usr/lib/alsa-lib"
fi
if [[ -f "/usr/share/alsa/alsa.conf" ]]; then
  export ALSA_CONFIG_PATH="/usr/share/alsa/alsa.conf"
fi
export ALSA_LOG_LEVEL=0

echo "📁 Base dir: $BASE_DIR"
cd "$BASE_DIR"

# ---------- conda init ----------
if [[ ! -f "$CONDA_SH" ]]; then
  echo "❌ conda.sh not found: $CONDA_SH"
  exit 1
fi
# shellcheck disable=SC1090
source "$CONDA_SH"

# ---------- time sync wait ----------
echo "⏰ Checking system time..."
while [ "$(date +%Y)" -lt 2025 ]; do
  echo "⏳ Waiting for time sync... $(date)"
  sleep 2
done
echo "✅ Time synced: $(date)"

# ---------- PulseAudio defaults (optional) ----------
if command -v pactl >/dev/null 2>&1; then
  echo "🔊 Checking audio server..."
  READY=0
  for _ in {1..20}; do
    if timeout 0.3s pactl info >/dev/null 2>&1; then
      READY=1
      break
    fi
    sleep 0.3
  done

  if [[ "$READY" -eq 1 ]]; then
    echo "🎧 Setting default speaker → $SINK"
    pactl set-default-sink "$SINK" || true
    echo "🎤 Setting default microphone → $SOURCE"
    pactl set-default-source "$SOURCE" || true
  else
    echo "⚠️ PulseAudio/PipeWire not ready. Continuing anyway."
  fi
else
  echo "⚠️ pactl not found. Skipping audio defaults."
fi

# ---------- paths check ----------
if [[ ! -f "$PY_FILE" ]]; then
  echo "❌ sanad_voice.py not found: $PY_FILE"
  exit 1
fi

# ---------- start teleimager server (py3.10) ----------
echo "🐍 Activating teleimager env: $ENV_TELE"
conda activate "$ENV_TELE"

echo "🐍 teleimager python: $(which python)"
python -c "import sys; print('✅ teleimager sys.executable:', sys.executable); print('✅ teleimager sys.version:', sys.version.split()[0])"

TELE_LOG="$BASE_DIR/main_teleimager.log"
echo "📷 Starting teleimager server (--rs) in background..."
python -m teleimager.image_server --rs >"$TELE_LOG" 2>&1 &
TELE_PID=$!
echo "✅ teleimager PID=$TELE_PID  log=$TELE_LOG"

cleanup() {
  echo ""
  echo "🧹 Cleaning up..."
  if kill -0 "$TELE_PID" >/dev/null 2>&1; then
    echo "🛑 Stopping teleimager server PID=$TELE_PID"
    kill "$TELE_PID" >/dev/null 2>&1 || true
    wait "$TELE_PID" >/dev/null 2>&1 || true
  fi
  echo "✅ Done."
}
trap cleanup EXIT INT TERM

# Give server time to start
sleep 2

# ---------- run sanad (py3.11) ----------
echo "🐍 Activating gemini env: $ENV_GEM"
conda activate "$ENV_GEM"

echo "🐍 gemini python: $(which python)"
python -c "import sys; print('✅ gemini sys.executable:', sys.executable); print('✅ gemini sys.version:', sys.version.split()[0])"

# Ensure unitree_sdk2py can import
export PYTHONPATH="$HOME/unitree_sdk2_python:${PYTHONPATH:-}"

echo "🔧 PYTHONPATH=$PYTHONPATH"
echo "🔧 ALSA_PLUGIN_DIR=${ALSA_PLUGIN_DIR:-"(not set)"}"
echo "🔧 ALSA_CONFIG_PATH=${ALSA_CONFIG_PATH:-"(not set)"}"
echo "🎥 CAMERA_DEVICE=$CAMERA_DEVICE"
echo "🖼️ PHOTO_PREFIX=$PHOTO_PREFIX"

echo "🚀 Starting Sanad Photographer..."
exec python "$PY_FILE"
