#!/usr/bin/env bash
# 一鍵分享「課本變遊戲」到公網（Cloudflare 免費 Quick Tunnel，免帳號）
#
# 用法：
#   bash share.sh                    # 開放分享（任何人只要有網址就能用）
#   bash share.sh --code 1234        # 需要存取碼（朋友要輸入 1234）
#   bash share.sh --port 5000        # 指定本機埠（預設 5000）
#
# 停止：
#   pkill -f "[s]erver.py"; pkill -f "[c]loudflared tunnel"
set -e
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$DIR"

CODE=""
PORT=5000
while [ $# -gt 0 ]; do
  case "$1" in
    --code) CODE="$2"; shift 2 ;;
    --port) PORT="$2"; shift 2 ;;
    *) echo "未知參數：$1"; exit 1 ;;
  esac
done

CF="$HOME/.local/bin/cloudflared"
if [ ! -x "$CF" ]; then
  echo "📥 未安裝 cloudflared，正在下載（免 sudo）…"
  mkdir -p "$HOME/.local/bin"
  curl -sL -o "$CF" https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64
  chmod +x "$CF"
fi

# --- 1) 啟動後端（含 AI 代理） ---
if curl -s --max-time 2 "http://127.0.0.1:${PORT}/api/health" >/dev/null; then
  echo "✅ 後端已在運行（port ${PORT}）"
else
  echo "🚀 啟動後端 server.py（port ${PORT}）…"
  STUDY_PORT="$PORT" STUDY_ACCESS_CODE="$CODE" nohup python3 server.py >/tmp/opencode/study-server.log 2>&1 &
  sleep 2
  if ! curl -s --max-time 3 "http://127.0.0.1:${PORT}/api/health" >/dev/null; then
    echo "❌ 後端啟動失敗，請看 /tmp/opencode/study-server.log"; exit 1
  fi
  echo "✅ 後端已啟動"
fi

# --- 2) 啟動 Cloudflare Quick Tunnel ---
echo "☁️  開啟 Cloudflare 隧道…"
pkill -f "[c]loudflared tunnel --url" 2>/dev/null || true
sleep 1
nohup "$CF" tunnel --url "http://127.0.0.1:${PORT}" --no-autoupdate >/tmp/opencode/cloudflared.log 2>&1 &

URL=""
for i in $(seq 1 30); do
  sleep 1
  URL="$(grep -oE 'https://[a-z0-9-]+\.trycloudflare\.com' /tmp/opencode/cloudflared.log | head -1 || true)"
  [ -n "$URL" ] && break
done

if [ -z "$URL" ]; then
  echo "❌ 未能取得公開網址，請看 /tmp/opencode/cloudflared.log"; exit 1
fi

cat <<EOF

============================================================
🎉 分享成功！把下面網址傳給朋友：

   ${URL}/study-maker.html

$( [ -n "$CODE" ] && echo "   🔒 存取碼（朋友首次使用要輸入）：${CODE}" || echo "   ⚠️  目前無存取碼：任何拿到網址的人都能使用你的電腦算力。" )
============================================================

ℹ️  注意事項
   • 這條網址每次重啟都會改變（Quick Tunnel 特性）
   • 朋友使用時，AI 運算在「你的電腦」進行（同時太多人會變慢）
   • 要加/改存取碼：重新執行  bash share.sh --code 你的密碼
   • 停止分享：
       pkill -f "[c]loudflared tunnel"
       pkill -f "[s]erver.py"
============================================================
EOF
