#!/bin/bash
# 分弦一键启动：Apple 芯片走轻量原生引擎，其余平台走 Demucs。
set -euo pipefail

cd "$(dirname "$0")"

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="${FENXUAN_RUNTIME:-../../runtime/fenxuan}"
VENV="$RUNTIME/venv"
export FENXUAN_DATA="$RUNTIME/data"
export TORCH_HOME="$RUNTIME/torch-home"
mkdir -p "$FENXUAN_DATA" "$RUNTIME/bin"

EXTRA_REQUIREMENTS=""
CHECK_IMPORTS='import fastapi, uvicorn, soundfile, imageio_ffmpeg'
if [ "$(uname -s)" = "Darwin" ] && [ "$(uname -m)" = "arm64" ]; then
  NATIVE="$RUNTIME/bin/demucs-rs-v0.3.4"
  ARCHIVE_SHA="bb6a6346392892ef3f172df0b60d97f4cb54aa38f7306ec129a60d786d261225"
  BINARY_SHA="759f93181b43e0d8935ab43617a1ff7fb79d338a83257ffbc0a0739686c97e9b"
  if [ ! -x "$NATIVE" ] || [ "$(shasum -a 256 "$NATIVE" | awk '{print $1}')" != "$BINARY_SHA" ]; then
    echo "首次运行，准备轻量分轨引擎（约 10MB）…"
    ARCHIVE="$NATIVE.tar.gz"
    curl -fL --retry 2 -o "$ARCHIVE" \
      https://github.com/nikhilunni/demucs-rs/releases/download/v0.3.4/demucs-aarch64-apple-darwin.tar.gz
    echo "$ARCHIVE_SHA  $ARCHIVE" | shasum -a 256 -c - >/dev/null
    tar -xzf "$ARCHIVE" -C "$RUNTIME/bin"
    mv "$RUNTIME/bin/demucs" "$NATIVE"
    chmod +x "$NATIVE"
    rm -f "$ARCHIVE"
  fi
  export FENXUAN_DEMUCS_BIN="$NATIVE"
  ENGINE_ID="native-v0.3.4"
else
  EXTRA_REQUIREMENTS="requirements-demucs.txt"
  CHECK_IMPORTS+='; import demucs, torch, torchaudio'
  ENGINE_ID="pytorch-demucs"
fi

REQ_HASH=$({ cat requirements.txt; printf '%s\n' "$ENGINE_ID"; \
  [ -z "$EXTRA_REQUIREMENTS" ] || cat "$EXTRA_REQUIREMENTS"; } \
  | shasum -a 256 | awk '{print $1}')
REQ_STAMP="$RUNTIME/requirements.sha256"
INSTALLED_HASH=""
[ ! -f "$REQ_STAMP" ] || INSTALLED_HASH=$(tr -d '[:space:]' < "$REQ_STAMP")
if [ ! -x "$VENV/bin/python" ] || [ "$REQ_HASH" != "$INSTALLED_HASH" ] \
    || ! "$VENV/bin/python" -c 'import sys; raise SystemExit(sys.version_info < (3, 10))'; then
  echo "更新精简运行环境…"
  "$BASE_PY" -m venv --clear "$VENV"
fi
if ! "$VENV/bin/python" -c "$CHECK_IMPORTS" >/dev/null 2>&1; then
  echo "安装分弦所需组件（首次约几分钟）…"
  "$VENV/bin/python" -m pip install --quiet --upgrade pip
  if [ -n "$EXTRA_REQUIREMENTS" ]; then
    "$VENV/bin/python" -m pip install --quiet -r requirements.txt -r "$EXTRA_REQUIREMENTS"
  else
    "$VENV/bin/python" -m pip install --quiet -r requirements.txt
  fi
  printf '%s\n' "$REQ_HASH" > "$REQ_STAMP"
fi

if [ "$ENGINE_ID" = "native-v0.3.4" ]; then
  # v1.6 只用原生六轨引擎；删除旧版已废弃、可重新下载的模型缓存。
  "$BASE_PY" - "$RUNTIME/sep-models" "$TORCH_HOME" <<'PY'
import shutil
import sys

for path in sys.argv[1:]:
    shutil.rmtree(path, ignore_errors=True)
PY
fi

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