#!/bin/bash
export PYTHONDONTWRITEBYTECODE=1
set -u

ROOT="$(cd "$(dirname "$0")" && pwd)"
LOG="$ROOT/start_mac.log"
ERR="$ROOT/start_mac.err"
CONFIG_DIR="$HOME/Library/Application Support/桌宠"
KEY_FILE="$CONFIG_DIR/deepseek_api_key"
PYTHON_BIN=""

show_error() {
  local message="$1"
  if command -v osascript >/dev/null 2>&1; then
    osascript -e "display dialog \"$message\" buttons {\"OK\"} default button \"OK\" with icon caution" >/dev/null 2>&1 || true
  fi
  echo "$message" >&2
}

find_python() {
  local candidates=(
    "/Library/Frameworks/Python.framework/Versions/3.13/bin/python3"
    "/Library/Frameworks/Python.framework/Versions/3.12/bin/python3"
    "/Library/Frameworks/Python.framework/Versions/3.11/bin/python3"
    "/opt/homebrew/bin/python3"
    "/usr/local/bin/python3"
  )
  for candidate in "${candidates[@]}"; do
    if [ -x "$candidate" ]; then
      echo "$candidate"
      return 0
    fi
  done
  command -v python3 2>/dev/null || true
}

cd "$ROOT" || exit 1
mkdir -p "$CONFIG_DIR"
: > "$LOG"
: > "$ERR"

PYTHON_BIN="$(find_python)"
if [ -z "$PYTHON_BIN" ]; then
  show_error "Mac 上没有找到 Python 3。请先安装 python.org 的 Python 3，再重新打开桌宠。"
  exit 1
fi

if [ -s "$KEY_FILE" ]; then
  export DEEPSEEK_API_KEY="$(tr -d '\r\n' < "$KEY_FILE")"
fi

if [ ! -x "$ROOT/.venv_mac/bin/python" ]; then
  "$PYTHON_BIN" -m venv "$ROOT/.venv_mac" >>"$LOG" 2>>"$ERR"
  if [ $? -ne 0 ]; then
    show_error "创建 Mac 运行环境失败。请打开 start_mac.err 看错误。"
    exit 1
  fi
fi

PYTHON_BIN="$ROOT/.venv_mac/bin/python"

"$PYTHON_BIN" - <<'PY' >/dev/null 2>&1
import PIL
import certifi
import PySide6
PY
if [ $? -ne 0 ]; then
  "$PYTHON_BIN" -m pip install --upgrade pip >>"$LOG" 2>>"$ERR"
  "$PYTHON_BIN" -m pip install pillow certifi PySide6 >>"$LOG" 2>>"$ERR"
  if [ $? -ne 0 ]; then
    show_error "安装运行组件失败。请打开 start_mac.err 看错误。"
    exit 1
  fi
fi

POS_ARGS=()
if [ ! -f "$CONFIG_DIR/pet_position_mac.txt" ]; then
  POS_ARGS=(--x 100 --y 100)
fi

export PYTHONIOENCODING=utf-8
"$PYTHON_BIN" "$ROOT/launch_pet.py" --renderer bibi "${POS_ARGS[@]}" "$@" >>"$LOG" 2>>"$ERR"
exit $?
