#!/bin/bash
# 分弦一键启动：自动修复运行环境，模型在真正使用时才下载。
set -euo pipefail

cd "$(dirname "$0")"

if ! command -v ffmpeg >/dev/null 2>&1 || ! command -v ffprobe >/dev/null 2>&1; then
  echo "缺少 ffmpeg。请先运行：brew install ffmpeg"
  exit 1
fi

BASE_PY=""
for candidate in "${FENXUAN_PYTHON:-}" python3.13 python3.12 python3.11 python3.10; do
  [ -n "$candidate" ] || continue
  if command -v "$candidate" >/dev/null 2>&1 \
      && "$candidate" -c 'import sys; raise SystemExit(sys.version_info < (3, 10))'; then
    BASE_PY="$(command -v "$candidate")"
    break
  fi
done
if [ -z "$BASE_PY" ]; then
  echo "分弦需要 Python 3.10 或以上版本。"
  echo "建议安装：brew install python@3.12"
  exit 1
fi

RUNTIME="../../runtime/fenxuan"
VENV="$RUNTIME/venv"
export FENXUAN_MODELS="$RUNTIME/sep-models"
export FENXUAN_DATA="$RUNTIME/data"
export TORCH_HOME="$RUNTIME/torch-home"
mkdir -p "$FENXUAN_DATA" "$FENXUAN_MODELS"

if [ ! -x "$VENV/bin/python" ]; then
  echo "首次运行，创建本机环境…"
  "$BASE_PY" -m venv "$VENV"
elif ! "$VENV/bin/python" -c 'import sys; raise SystemExit(sys.version_info < (3, 10))'; then
  echo "发现旧版 Python 环境，正在自动重建…"
  "$BASE_PY" -m venv --clear "$VENV"
fi

REQ_HASH=$(shasum -a 256 requirements.txt | awk '{print $1}')
REQ_STAMP="$RUNTIME/requirements.sha256"
INSTALLED_HASH=""
[ ! -f "$REQ_STAMP" ] || INSTALLED_HASH=$(tr -d '[:space:]' < "$REQ_STAMP")
if [ "$REQ_HASH" != "$INSTALLED_HASH" ] \
    || ! "$VENV/bin/python" -c 'import fastapi, uvicorn, demucs, soundfile; from audio_separator.separator import Separator' >/dev/null 2>&1; then
  echo "安装分弦所需组件（首次约几分钟）…"
  "$VENV/bin/python" -m pip install --quiet --upgrade pip
  "$VENV/bin/python" -m pip install --quiet -r requirements.txt
  printf '%s\n' "$REQ_HASH" > "$REQ_STAMP"
fi

echo "分弦已启动 → http://127.0.0.1:8642"
# 让系统界面和其他应用优先响应；不会降低输出音质。
exec nice -n 10 "$VENV/bin/python" server/app.py
