#!/usr/bin/env bash
# ========================================
# 前端构建并发布到 Cloudflare Pages
# 用法：
#   API_BASE=https://your-domain/api ./deploy/build-and-deploy.sh
#   或 API_BASE=http://47.xx.xx.xx/api ./deploy/build-and-deploy.sh
# 项目名固定：aipro-skill（已存在的 Pages 项目）
# ========================================
set -euo pipefail

cd "$(dirname "$0")/.."

: "${API_BASE:?请先设置 API_BASE，例如 export API_BASE=https://api.your-domain.com/api}"

PROJECT=aipro-skill

echo "==> [1/3] 写入 .env.production"
cat > .env.production <<EOF
VITE_USE_MOCK=false
VITE_API_BASE=${API_BASE}
EOF

echo "==> [2/3] vite build"
npm run build

echo "==> [3/3] wrangler pages deploy"
npx --yes wrangler pages deploy dist \
  --project-name "${PROJECT}" \
  --branch main \
  --commit-dirty=true

echo
echo "✅ 前端已发布"
echo "   线上地址: https://${PROJECT}.pages.dev"
echo "   后端 API: ${API_BASE}"
