#!/usr/bin/env bash
# 发布后健康检查:可达性 + Content-Type + 【是否被强制下载】
# 用法: verify.sh <url>
#
# 失败语义（spec 2026-06-03-app-builder-publish-scaffold-design follow-up）：
#   首页非 200 / 检测到 Content-Disposition 强制下载 → exit 1。
#   publish.sh 不加 `|| true` 兜底，verify 失败会让 publish.sh 整体 exit 非 0，
#   触发 daemon runner 的 publish-failed 路径：广播帧 + 回灌 chat user_text 让 assistant 接管修复。
#
# 信息原则：失败原因 echo 到 stderr（runner 的 errorSummary 抠 stderr 最后 20 行）。
set -euo pipefail
URL="${1:?用法: verify.sh <url>}"

echo "== 健康检查: $URL =="
code=$(curl -s -o /dev/null -w "%{http_code}" --max-time 30 "$URL/" || echo 000)
ctype=$(curl -s -o /dev/null -w "%{content_type}" --max-time 30 "$URL/" || echo "")
echo "首页: HTTP $code  ($ctype)"

# 关键检查: 有 Content-Disposition 说明会被浏览器当文件下载(没绑自定义域名的典型症状)
hdr=$(curl -s -D - -o /dev/null --max-time 30 "$URL/" || true)
has_cd=0
if echo "$hdr" | grep -qi 'content-disposition'; then
  has_cd=1
  echo "❌ 检测到 Content-Disposition —— 浏览器会下载而非渲染!确认走的是 fc3-domain 自定义域名,而不是 fcapp.run" >&2
else
  echo "✓ 无 Content-Disposition,浏览器可正常渲染网页"
fi

if [ "$code" = "200" ] && [ "$has_cd" = "0" ]; then
  echo "✓ 全链路 OK"
  exit 0
fi

# 失败：原因写 stderr 供 runner 抠成 errorSummary，UI / assistant 都能看清楚
if [ "$code" != "200" ]; then
  echo "❌ verify failed: 首页 HTTP $code (期望 200)；查 s logs 找原因" >&2
fi
exit 1
