#!/usr/bin/env bash
set -euo pipefail

check() {
  local name="$1"
  local url="$2"
  shift 2
  local code
  code="$(curl -sS -o /dev/null -w "%{http_code}" "$@" "$url" || echo "000")"
  if [[ "$code" == "200" ]]; then
    echo "OK  $name ($url)"
  else
    echo "FAIL $name ($url) -> HTTP $code"
    return 1
  fi
}

failed=0
check "API gateway" "http://127.0.0.1:8890/api/v1/health" || failed=1
check "Vite frontend" "http://127.0.0.1:5173/" || failed=1
check "nginx /health" "http://127.0.0.1/health" || failed=1
check "nginx /api" "http://127.0.0.1/api/v1/health" "-H" "Host: threads-tool.30cm.net" || failed=1

if [[ "$failed" -ne 0 ]]; then
  echo
  echo "修復方式："
  echo "  終端 1: cd thread-master/backend && make run"
  echo "  終端 2: cd thread-master && make web-dev"
  exit 1
fi

echo
echo "開發環境正常，可開啟 https://threads-tool.30cm.net"