#!/bin/bash
set -e

APP_DIR="$HOME/.codjz-gpt-local"
BASE_URL="https://codjz.com/downloads/mac-runtime"

mkdir -p "$APP_DIR"
cd "$APP_DIR"

echo "============================================================"
echo "  橘子GPT批量检测-本地版本 Mac"
echo "  本地地址：http://127.0.0.1:5007"
echo "============================================================"

if ! command -v python3 >/dev/null 2>&1; then
  echo "没有找到 python3。请先安装 Python 3，然后重新打开本程序。"
  echo "下载地址：https://www.python.org/downloads/macos/"
  read -r -p "按回车退出..."
  exit 1
fi

if [ ! -d "/Applications/Google Chrome.app" ]; then
  echo "没有找到 Google Chrome。请先安装 Chrome，然后重新打开本程序。"
  echo "下载地址：https://www.google.com/chrome/"
  read -r -p "按回车退出..."
  exit 1
fi

download_file() {
  local name="$1"
  local target="$2"
  if command -v curl >/dev/null 2>&1; then
    curl -fsSL "$BASE_URL/$name" -o "$target"
  else
    python3 - "$BASE_URL/$name" "$target" <<'PY'
import sys
import urllib.request
urllib.request.urlretrieve(sys.argv[1], sys.argv[2])
PY
  fi
}

echo "正在准备本地文件..."
mkdir -p templates turnstilePatch assets
download_file "gpt_checker_all_reconstructed.py" "gpt_checker_all_reconstructed.py"
download_file "requirements.txt" "requirements.txt"
download_file "index.html" "templates/index.html"
download_file "manifest.json" "turnstilePatch/manifest.json"
download_file "script.js" "turnstilePatch/script.js"
download_file "logo.png" "assets/logo.png"
download_file "favicon.png" "assets/favicon.png"

if [ ! -d ".venv" ]; then
  echo "首次运行，正在创建本地环境..."
  python3 -m venv .venv
fi

source ".venv/bin/activate"
python -m pip install --upgrade pip
python -m pip install -r requirements.txt

export GPT_CHECKER_PORT="${GPT_CHECKER_PORT:-5007}"
python gpt_checker_all_reconstructed.py
