#!/usr/bin/env bash
# 将 plaza.tkmind.cn 经 Cloudflare Tunnel 指到本机 Plaza（:3001）
#
# 前置：
#   1. cloudflared 已安装且 ollama-tkmind 隧道在跑
#   2. pnpm dev:plaza 或 next start 监听 :3001
#
# 用法：pnpm setup:plaza-tunnel
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
CF_CONFIG="${CLOUDFLARE_TUNNEL_CONFIG:-/Users/john/Project/ollama/cloudflare/config.yml}"
TUNNEL_NAME="${CLOUDFLARE_TUNNEL_NAME:-ollama-tkmind}"
PLAZA_HOST="${PLAZA_LOCAL_HOST:-plaza.tkmind.cn}"
PLAZA_PORT="${PLAZA_TUNNEL_PORT:-${PLAZA_PORT:-3001}}"
GUI="gui/$(id -u)"

chmod +x "${ROOT}/scripts/patch-plaza-tunnel-config.mjs"

echo "==> 更新 cloudflared ingress（${PLAZA_HOST} → 127.0.0.1:${PLAZA_PORT}）"
CLOUDFLARE_TUNNEL_CONFIG="${CF_CONFIG}" PLAZA_TUNNEL_PORT="${PLAZA_PORT}" \
  node "${ROOT}/scripts/patch-plaza-tunnel-config.mjs"

echo "==> 注册 DNS 路由（${PLAZA_HOST} → 隧道 ${TUNNEL_NAME}）"
if cloudflared tunnel route dns list 2>/dev/null | grep -q "${PLAZA_HOST}"; then
  echo "DNS 路由已存在，跳过"
else
  cloudflared tunnel route dns "${TUNNEL_NAME}" "${PLAZA_HOST}" || {
    echo "⚠  DNS 路由失败（可能已在 Cloudflare 控制台手动配置）。继续重启 cloudflared…" >&2
  }
fi

echo "==> 重启 cloudflared"
launchctl kickstart -k "${GUI}/com.cloudflare.cloudflared" 2>/dev/null || {
  echo "⚠  未找到 LaunchAgent com.cloudflare.cloudflared，请手动：cloudflared tunnel --config ${CF_CONFIG} run" >&2
}

sleep 2
echo ""
echo "=== Plaza 隧道状态 ==="
curl -s -o /dev/null -w "本机 Plaza :${PLAZA_PORT}/plaza → %{http_code}\n" \
  "http://127.0.0.1:${PLAZA_PORT}/plaza" 2>/dev/null || echo "本机 Plaza 未运行（请先 pnpm dev:plaza）"
curl -s -o /dev/null -w "外网 ${PLAZA_HOST}/plaza → %{http_code}\n" \
  "https://${PLAZA_HOST}/plaza" 2>/dev/null || true
echo ""
echo "日志: ~/Library/Logs/com.cloudflare.cloudflared.log（或 launchctl 配置的路径）"
echo "配置: ${CF_CONFIG}"
