#!/usr/bin/env bash
# OCR Worker screen 管理（主程序同机部署时使用）
set -euo pipefail

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

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

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

  start    启动 OCR Worker（screen 后台，GPU 常驻）
  stop     停止 screen 会话
  restart  重启
  status   查看 screen / health / GPU
  attach   进入 screen 终端（Ctrl+A D 退出）

EOF
}

cmd="${1:-status}"

case "${cmd}" in
  start)
    start_ocr_screen
    wait_ocr_healthy || true
    ;;
  stop)
    stop_ocr_screen
    ;;
  restart)
    stop_ocr_screen
    sleep 1
    start_ocr_screen
    wait_ocr_healthy || true
    ;;
  status)
    show_ocr_status
    ;;
  attach)
    if ocr_screen_running; then
      screen -r "${OCR_SCREEN_NAME}"
    else
      log_error "screen 未运行，请先: bash deploy/ocr-screen.sh start"
      exit 1
    fi
    ;;
  *)
    usage
    exit 1
    ;;
esac
