#!/usr/bin/env bash
# OCR Worker 管理（systemd 开机自启；兼容旧 screen 命令）
set -euo pipefail

INSTALL_DIR="${INSTALL_DIR:-/opt/secondary-school-grade-archive}"

# shellcheck source=ocr-common.sh
source "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/ocr-common.sh"

# 最小日志（单独运行时）
if ! declare -F log_info >/dev/null 2>&1; then
  RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; NC='\033[0m'
  log_info()  { echo -e "${GREEN}[INFO]${NC} $*"; }
  log_warn()  { echo -e "${YELLOW}[WARN]${NC} $*"; }
  log_error() { echo -e "${RED}[ERROR]${NC} $*" >&2; }
fi

usage() {
  cat <<EOF
用法: bash deploy/ocr-screen.sh <命令>

  start    启动 OCR（systemd，开机自启）
  stop     停止 OCR
  restart  重启 OCR
  status   查看服务 / health
  enable   仅注册开机自启（不重启）
  logs     跟踪日志
EOF
}

cmd="${1:-status}"
case "${cmd}" in
  start)
    start_ocr_service
    wait_ocr_healthy || true
    show_ocr_status
    ;;
  stop)
    stop_ocr_service
    log_info "OCR 已停止"
    ;;
  restart)
    stop_ocr_service
    start_ocr_service
    wait_ocr_healthy || true
    show_ocr_status
    ;;
  status)
    show_ocr_status
    ;;
  enable)
    setup_ocr_systemd
    log_info "已 enable，启动请: bash deploy/ocr-screen.sh start"
    ;;
  logs)
    journalctl -u "${OCR_SERVICE_NAME}" -f
    ;;
  attach)
    log_warn "OCR 已改为 systemd，不再使用 screen attach"
    log_info "查看日志: journalctl -u ${OCR_SERVICE_NAME} -f"
    ;;
  -h|--help|help)
    usage
    ;;
  *)
    usage
    exit 1
    ;;
esac
