#!/bin/bash
# thin-shell-smoke.sh — 薄殼防複發機制層 2（thin-shell-alignment SDD / issue #11 R4）
#
# 目的：讓「薄殼打了不存在的 server 端點」（死端點假綠）當場現形。
#   對 CLI/MCP 各能力對應的 cypher-executor 端點打一次，斷言 **非 404**。
#   404 = route 不存在 = 死端點 → 紅燈。其他狀態（401/400/200…）= 端點存在 → 綠。
#
# ⚠️ flag 紅線（SDD C2/R4.2）：本機/手動跑，**非 CI、非 cron、非輪詢**。
#   宣稱「CLI/MCP 對齊/完成」前手動跑一次即可。對齊「執行鏈路不依賴 CI」鐵律。
#
# 用法：
#   CYPHER_URL=https://cypher.arcrun.dev ./scripts/thin-shell-smoke.sh
#   （self-hosted：CYPHER_URL=https://<你的 cypher>.workers.dev ...）
#   不帶 API key 也能驗端點存在性（401 仍算「端點活著」）。帶 key 可更深驗：
#   ARCRUN_API_KEY=xxx CYPHER_URL=... ./scripts/thin-shell-smoke.sh

set -o pipefail

CYPHER_URL="${CYPHER_URL:-https://cypher.arcrun.dev}"
CYPHER_URL="${CYPHER_URL%/}"
API_KEY="${ARCRUN_API_KEY:-}"

PASS=0
FAIL=0
declare -a DEAD=()

# probe METHOD PATH LABEL
#   斷言端點非 404。404 → 死端點（紅）。連線失敗 → 紅（但標明是網路非死端點）。
probe() {
  method="$1"; path="$2"; label="$3"
  url="${CYPHER_URL}${path}"

  if [ "$method" = "POST" ]; then
    if [ -n "$API_KEY" ]; then
      code=$(curl -s -o /dev/null -w '%{http_code}' --max-time 15 -X POST -H "X-Arcrun-API-Key: ${API_KEY}" -H 'Content-Type: application/json' -d '{}' "$url" 2>/dev/null)
    else
      code=$(curl -s -o /dev/null -w '%{http_code}' --max-time 15 -X POST -H 'Content-Type: application/json' -d '{}' "$url" 2>/dev/null)
    fi
  else
    if [ -n "$API_KEY" ]; then
      code=$(curl -s -o /dev/null -w '%{http_code}' --max-time 15 -H "X-Arcrun-API-Key: ${API_KEY}" "$url" 2>/dev/null)
    else
      code=$(curl -s -o /dev/null -w '%{http_code}' --max-time 15 "$url" 2>/dev/null)
    fi
  fi
  code="${code:-000}"

  if [ "$code" = "000" ]; then
    echo "  ⚠️  $label — 連線失敗（網路/DNS，非死端點判定）：$method $path"
    FAIL=$((FAIL+1))
  elif [ "$code" = "404" ]; then
    echo "  ❌ $label — 死端點 404：$method $path"
    DEAD+=("$label: $method $path")
    FAIL=$((FAIL+1))
  else
    echo "  ✅ $label — 端點存在（HTTP ${code}）：$method $path"
    PASS=$((PASS+1))
  fi
}

echo "=== thin-shell smoke：對 ${CYPHER_URL} 驗端點存在性（斷言非 404）==="
echo ""
echo "── 薄殼核心能力（CLI/MCP 共用端點）──"
# 部署：CLI acr push / MCP u6u_deploy_workflow（方向①收斂後同此）
probe POST /webhooks/named "deploy(push)"
# 執行已部署：CLI acr run <name> / MCP u6u_execute_workflow（#11 P0 修的）
probe POST /webhooks/named/__smoke__/trigger "run(trigger)"
# 執行本機 YAML：/cypher/execute
probe POST /cypher/execute "execute"
# list：CLI acr list / MCP u6u_list_workflows（#11 P1 收斂的）
probe GET  /webhooks/named "list"
# search workflow：MCP u6u_search_workflows（#8 新增）
probe GET  "/workflows/search?q=smoke" "search_workflow"
# 驗證：MCP arcrun_validate_yaml
probe POST /validate "validate"
# backfill search entries（#8）
probe POST /workflows/backfill-search-entries "backfill"

echo ""
echo "── 其他薄殼端點 ──"
probe GET  /me "whoami"
probe POST /credentials "creds_push"
probe POST /recipes "recipe"
probe GET  /kbdb/templates "kbdb_templates"
probe POST /cypher/search "validate_local_graph(cypher/search)"

echo ""
echo "=== 結果：${PASS} 端點存在 / ${FAIL} 異常 ==="
if [ ${#DEAD[@]} -gt 0 ]; then
  echo ""
  echo "🔴 死端點（route 不存在，薄殼打了會 404）："
  for d in "${DEAD[@]}"; do echo "   - $d"; done
  echo ""
  echo "→ 修法：對照 cli-mcp-capability-matrix.md，把薄殼改打存在的 route，或補 server route。"
  exit 1
fi
echo "✅ 無死端點。"
