#!/usr/bin/env bash
# OCR Worker 一键诊断
set -uo pipefail

ROOT="$(cd "$(dirname "$0")" && pwd)"
PORT="${OCR_PORT:-23567}"
VENV="${ROOT}/.venv"

echo "========== OCR Worker 诊断 =========="
echo "目录: ${ROOT}"
echo "端口: ${PORT}"
echo ""

echo "--- 1. 虚拟环境 ---"
if [[ -d "${VENV}" ]]; then
  echo "OK  .venv 存在"
else
  echo "FAIL 未安装，请运行: bash install.sh"
fi

echo ""
echo "--- 2. 端口监听 ---"
if command -v ss >/dev/null; then
  if ss -tln | grep -q ":${PORT} "; then
    echo "OK  端口 ${PORT} 正在监听"
    ss -tlnp | grep ":${PORT} " || true
  else
    echo "FAIL 端口 ${PORT} 无服务 — 请先启动:"
    echo "      OCR_USE_GPU=true bash start.sh"
    echo "  或: sudo bash install-service.sh"
  fi
else
  netstat -tln 2>/dev/null | grep ":${PORT} " || echo "FAIL 端口 ${PORT} 无服务"
fi

echo ""
echo "--- 3. HTTP 健康检查 ---"
if command -v curl >/dev/null; then
  resp="$(curl -sS -m 3 "http://127.0.0.1:${PORT}/health" 2>&1)" || true
  if [[ -n "${resp}" ]]; then
    echo "OK  ${resp}"
  else
    echo "FAIL curl 无响应（服务未启动或启动失败）"
  fi
else
  echo "跳过（无 curl）"
fi

echo ""
echo "--- 4. GPU ---"
if command -v nvidia-smi >/dev/null; then
  nvidia-smi --query-gpu=name,memory.used,memory.total --format=csv,noheader
else
  echo "未检测到 nvidia-smi"
fi

echo ""
echo "--- 5. Python 依赖 ---"
if [[ -d "${VENV}" ]]; then
  # shellcheck disable=SC1091
  source "${VENV}/bin/activate"
  python3 - <<'PY' || true
try:
    import paddle
    print("OK  paddle", paddle.__version__)
except Exception as e:
    print("FAIL paddle:", e)
try:
    import paddleocr
    print("OK  paddleocr")
except Exception as e:
    print("FAIL paddleocr:", e)
try:
    import fastapi, uvicorn
    print("OK  fastapi/uvicorn")
except Exception as e:
    print("FAIL fastapi:", e)
PY
fi

echo ""
echo "--- 6. systemd ---"
if systemctl is-active ocr-worker &>/dev/null; then
  systemctl status ocr-worker --no-pager -l | head -15
elif [[ -f /etc/systemd/system/ocr-worker.service ]]; then
  echo "服务已安装但未运行: sudo systemctl start ocr-worker"
else
  echo "未安装 systemd 服务（可选）: sudo bash install-service.sh"
fi

echo "===================================="
