#!/usr/bin/env bash
# 注册 OCR Worker 为 systemd 服务（后台常驻 + 开机自启）
# 推荐：由 deploy/install.sh / update.sh 自动调用；也可单独执行。
set -euo pipefail

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

# shellcheck source=../ocr-common.sh
source "$(cd "$(dirname "$0")/.." && pwd)/ocr-common.sh"

# 提供最小 log_*，以便单独运行
if ! declare -F log_info >/dev/null 2>&1; then
  log_info()  { echo "[INFO] $*"; }
  log_warn()  { echo "[WARN] $*"; }
  log_error() { echo "[ERROR] $*" >&2; }
fi

if [[ "${EUID:-$(id -u)}" -ne 0 ]]; then
  echo "请使用 root 运行: sudo bash install-service.sh"
  exit 1
fi

if [[ ! -d "${ROOT}/.venv" ]]; then
  echo "请先运行: bash ${ROOT}/install.sh"
  exit 1
fi

chmod +x "${ROOT}/start.sh" "${ROOT}/check.sh" "${ROOT}/install.sh" 2>/dev/null || true

start_ocr_service
wait_ocr_healthy 20 || true

echo ""
echo "==> 服务状态:"
systemctl status ocr-worker --no-pager -l | head -20

echo ""
echo "==> 健康检查:"
curl -sS "http://127.0.0.1:${PORT}/health" || echo "（尚未就绪，请稍等后: curl http://127.0.0.1:${PORT}/health）"
echo ""
echo "管理: systemctl status|restart|stop ocr-worker"
echo "日志: journalctl -u ocr-worker -f"
