#!/bin/bash
# mac-tunnel.app 启动器：挑一个 Tk 版本够新的 python3 来跑界面
set -u
HERE="$(cd "$(dirname "$0")/.." && pwd)"
GUI="$HERE/Resources/mactunnel_gui.py"
ROOT="$HOME/.mac-tunnel"
LAUNCH_LOG="$ROOT/launcher.log"
GUI_LOG="$ROOT/gui.log"
mkdir -p "$ROOT"

# 为什么必须挑 python：
#   macOS 系统自带的 /usr/bin/python3 用的是 Apple 的 Tcl/Tk **8.5.9**，
#   那是 Python 官方文档明确点名「在 macOS 上有严重 bug，别用」的版本 ——
#   实际表现就是窗口一片白 + python 进程 CPU 100%。
#   所以优先用 Tk >= 8.6 的 python，系统那个只当最后兜底。
#
# classify 退出码：0 = 可用且 Tk>=8.6（首选）；2 = 可用但 Tk<8.6（兜底）；9 = 不可用
classify() {
  local py="$1"
  [ -x "$py" ] || return 9
  "$py" - <<'PY' 2>/dev/null
import sys
try:
    import tkinter
except Exception:
    raise SystemExit(9)
raise SystemExit(0 if tkinter.TkVersion >= 8.6 else 2)
PY
}

PY=""
FALLBACK=""
for cand in /opt/homebrew/bin/python3 /usr/local/bin/python3 \
            "$(command -v python3 2>/dev/null || true)" \
            /usr/bin/python3 \
            /opt/homebrew/opt/python@3.12/bin/python3 \
            /opt/homebrew/opt/python@3.11/bin/python3; do
  [ -n "$cand" ] || continue
  classify "$cand"
  rc=$?
  if [ "$rc" = "0" ]; then PY="$cand"; break; fi
  if [ "$rc" = "2" ] && [ -z "$FALLBACK" ]; then FALLBACK="$cand"; fi
  PY=""
done

if [ -z "$PY" ] && [ -n "$FALLBACK" ]; then
  PY="$FALLBACK"
  osascript -e 'display dialog "mac-tunnel 只能找到系统自带的旧图形库（Tcl/Tk 8.5.9），它会让窗口白屏。\n\n请装一个新版 python3 再打开本 App（任选一个）：\n1) 终端执行：brew install python-tk\n2) 或到 python.org 下载安装 python3\n\n装完重新双击本 App 即可。" buttons {"好"} default button 1 with icon caution with title "mac-tunnel"' >/dev/null 2>&1
fi

if [ -z "$PY" ]; then
  # 完全没有可用的 python3 + tkinter：给出可操作的提示，而不是静默失败
  osascript -e 'display dialog "mac-tunnel 需要 macOS 上的 python3（含 tkinter）。\n\n解决办法（任选一个）：\n1) 终端执行：brew install python-tk\n2) 或到 python.org 下载安装 python3\n\n装完重新双击本 App 即可。" buttons {"好"} default button 1 with icon caution with title "mac-tunnel"' >/dev/null 2>&1
  echo "$(date '+%F %T') 找不到带 tkinter 的 python3" >> "$LAUNCH_LOG"
  exit 1
fi

TKVER="$("$PY" -c 'import tkinter;print(tkinter.TkVersion)' 2>/dev/null || echo '?')"
echo "$(date '+%F %T') 用 $PY (Tk $TKVER) 启动界面" >> "$LAUNCH_LOG"

# 界面进程的错误输出以前没人接（双击时直接丢了）→ 白屏时看不到任何线索。
# 现在一律写进 ~/.mac-tunnel/gui.log（每次启动覆盖，只留最近一次）。
exec "$PY" "$GUI" >"$GUI_LOG" 2>&1
