#!/usr/bin/env bash
# 上传后自检：代码是否到位、.env 是否含 Flock、容器是否在跑旧镜像
# 用法：cd /home/project/chajia && bash deploy/verify-upload-bt-host-mysql.sh

set -euo pipefail

ROOT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
ENV_FILE="${ROOT_DIR}/.env"
COMPOSE_FILE="${ROOT_DIR}/deploy/docker-compose.bt-host-mysql.yml"

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

ok() { echo -e "${GREEN}[OK]${NC} $*"; }
bad() { echo -e "${RED}[缺]${NC} $*"; }
warn() { echo -e "${YELLOW}[注意]${NC} $*"; }

cd "$ROOT_DIR"
fail=0

echo "=== 1) 磁盘上的新代码（上传是否落到正确目录）==="
for p in \
  "app/api/flock/quotes/route.ts" \
  "workers/rpa/flock-freight.ts" \
  "workers/rpa/mothership-logged-in-quote.ts" \
  "deploy/update-code-only-bt-host-mysql.sh" \
  "deploy/datagrip-manual-migrate-20260716.sql"
do
  if [[ -f "$ROOT_DIR/$p" ]]; then ok "有 $p"; else bad "无 $p"; fail=1; fi
done

echo ""
echo "=== 2) .env 新参数（不重建也会导致前端看不到 Flock）==="
if [[ ! -f "$ENV_FILE" ]]; then
  bad "没有 .env"
  fail=1
else
  for key in FLOCK_RPA_ENABLED FLOCK_QUOTE_MODE NEXT_PUBLIC_FLOCK_POLL_TIMEOUT_MS; do
    if grep -qE "^[[:space:]]*${key}=" "$ENV_FILE"; then
      ok "$key=$(grep -E "^[[:space:]]*${key}=" "$ENV_FILE" | tail -1 | cut -d= -f2-)"
    else
      bad ".env 缺少 $key"
      fail=1
    fi
  done
  if grep -qE "^[[:space:]]*RPA_BROWSER_CHANNEL=chrome" "$ENV_FILE"; then
    bad "存在 RPA_BROWSER_CHANNEL=chrome（Docker 会挂，请删除）"
    fail=1
  else
    ok "未设置 RPA_BROWSER_CHANNEL=chrome"
  fi
fi

echo ""
echo "=== 3) 容器是否在跑（上传源码不会自动进镜像）==="
if docker compose --env-file "$ENV_FILE" -f "$COMPOSE_FILE" ps 2>/dev/null | grep -q next-app; then
  docker compose --env-file "$ENV_FILE" -f "$COMPOSE_FILE" ps
  warn "若刚上传代码但未执行 update-code-only，容器仍是旧镜像 → 页面无新功能"
else
  bad "compose 未检测到 next-app，请检查路径/compose 文件"
  fail=1
fi

echo ""
echo "=== 4) 结论 ==="
if [[ $fail -ne 0 ]]; then
  bad "自检未通过。先补齐缺失项，再执行："
  echo "  bash deploy/update-code-only-bt-host-mysql.sh"
  exit 1
fi

ok "磁盘代码与 .env 看起来齐全。"
warn "若页面仍是旧版：必须重建镜像（上传 ≠ 生效）："
echo "  bash deploy/update-code-only-bt-host-mysql.sh"
echo "  docker compose --env-file .env -f deploy/docker-compose.bt-host-mysql.yml exec redis redis-cli FLUSHDB"
