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

WEB_URL=${WEB_URL:-"http://localhost:8080"}
API_URL=${API_URL:-"http://master.argus.com/api/v1/master/nodes"}
TIMEOUT=10

GREEN="\033[1;32m"
RED="\033[1;31m"
YELLOW="\033[1;33m"
RESET="\033[0m"

echo "[info] 测试 Argus Web 前端启动状态..."
echo "--------------------------------------------------"

# 等待 web 前端可用
attempt=1
while (( attempt <= 10 )); do
  if curl -fsS -m "$TIMEOUT" -o /dev/null "$WEB_URL"; then
    echo "[ok] Web 前端已启动 (${attempt}/10)"
    break
  fi
  echo "[..] 等待 Web 前端启动中 (${attempt}/10)"
  sleep 3
  (( attempt++ ))
done

if (( attempt > 10 )); then
  echo "[err] Web 前端在 30 秒内未启动"
  exit 1
fi

# 1. 检查首页可访问性
echo "[test] 检查首页访问..."
if curl -fsS "$WEB_URL" -m "$TIMEOUT" | grep -q "<title>"; then
  echo -e "[${GREEN}ok${RESET}] 首页可访问"
else
  echo -e "[${RED}err${RESET}] 首页访问失败"
  exit 1
fi

# 2. 检查静态资源加载
echo "[test] 检查静态资源..."
if curl -fsS "$WEB_URL/static/js" -m "$TIMEOUT" | grep -q "Cannot GET"; then
  echo -e "[${YELLOW}warn${RESET}] 静态资源路径可能未正确配置"
else
  echo -e "[${GREEN}ok${RESET}] 静态资源服务正常"
fi

# 3. 检查前端路由兼容
echo "[test] 检查 React Router 路由兼容..."
if curl -fsS "$WEB_URL/dashboard" -m "$TIMEOUT" | grep -q "<title>"; then
  echo -e "[${GREEN}ok${RESET}] React Router 路由兼容正常"
else
  echo -e "[${YELLOW}warn${RESET}] /dashboard 路由未正确返回 index.html"
fi

# 4. 测试 API 代理访问
echo "[test] 检查 API 代理..."
if curl -fsS "$API_URL" -m "$TIMEOUT" | grep -q "nodes"; then
  echo -e "[${GREEN}ok${RESET}] API 代理成功"
else
  echo -e "[${YELLOW}warn${RESET}] API 代理请求失败，请检查 Nginx proxy_pass"
fi

# 5. 页面关键字验证
echo "[test] 检查关键内容..."
if curl -fsS "$WEB_URL" | grep -q "Argus"; then
  echo -e "[${GREEN}ok${RESET}] 页面包含关键字 'Argus'"
else
  echo -e "[${YELLOW}warn${RESET}] 页面内容中未找到 'Argus'"
fi

# 6. DNS 检查
echo "[test] 检查 DNS 解析..."
if dig +short web.argus.com >/dev/null; then
  echo -e "[${GREEN}ok${RESET}] 域名 web.argus.com 解析正常"
else
  echo -e "[${YELLOW}warn${RESET}] 域名 web.argus.com 解析失败"
fi

# 7. 响应时间测试
echo "[test] 检查响应时间..."
response_time=$(curl -o /dev/null -s -w "%{time_total}\n" "$WEB_URL")
echo "[info] 响应时间: ${response_time}s"
if (( $(echo "$response_time > 2.0" | bc -l) )); then
  echo -e "[${YELLOW}warn${RESET}] 响应时间较慢（>2s）"
else
  echo -e "[${GREEN}ok${RESET}] 响应时间正常"
fi

echo "--------------------------------------------------"
echo "[done] Web 前端测试完成 ✅"
