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

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
DAEMON="${REPO_ROOT}/scripts/eyesis_host_daemon.py"

QUEUE_DIR="${EYESIS_HOST_QUEUE_DIR:-${REPO_ROOT}/attic/session-logs/eyesis-host-daemon}"
STATE_DIR="${QUEUE_DIR}"
PID_FILE="${STATE_DIR}/daemon.pid"
LOG_FILE="${EYESIS_HOST_DAEMON_LOG:-${REPO_ROOT}/attic/session-logs/eyesis_host_daemon.log}"
POLL_MS="${EYESIS_HOST_DAEMON_POLL_MS:-200}"
FORCE=0
LINES=80

usage() {
  cat <<'USAGE'
Usage:
  scripts/eyesis_host_daemon_ctl.sh start [--queue-dir DIR] [--log FILE] [--poll-ms N]
  scripts/eyesis_host_daemon_ctl.sh stop [--force] [--queue-dir DIR]
  scripts/eyesis_host_daemon_ctl.sh restart [options]
  scripts/eyesis_host_daemon_ctl.sh status [--queue-dir DIR]
  scripts/eyesis_host_daemon_ctl.sh logs [--lines N] [--log FILE]

Environment overrides:
  EYESIS_HOST_QUEUE_DIR, EYESIS_HOST_DAEMON_LOG, EYESIS_HOST_DAEMON_POLL_MS
USAGE
}

is_running() {
  [[ -f "${PID_FILE}" ]] || return 1
  local pid
  pid="$(cat "${PID_FILE}" 2>/dev/null || true)"
  [[ -n "${pid}" ]] || return 1
  kill -0 "${pid}" 2>/dev/null
}

clear_stale() {
  if [[ -f "${PID_FILE}" ]] && ! is_running; then
    rm -f "${PID_FILE}"
  fi
}

start_daemon() {
  mkdir -p "${QUEUE_DIR}" "${REPO_ROOT}/attic/session-logs"
  clear_stale
  if is_running; then
    echo "daemon: running (pid=$(cat "${PID_FILE}"))"
    return 0
  fi
  nohup "${DAEMON}" serve --queue-dir "${QUEUE_DIR}" --poll-ms "${POLL_MS}" >>"${LOG_FILE}" 2>&1 &
  echo $! >"${PID_FILE}"
  sleep 0.3
  if is_running; then
    echo "daemon: started (pid=$(cat "${PID_FILE}"))"
    echo "queue: ${QUEUE_DIR}"
    echo "log: ${LOG_FILE}"
    return 0
  fi
  echo "daemon: failed to start" >&2
  return 1
}

stop_daemon() {
  clear_stale
  if ! is_running; then
    echo "daemon: stopped"
    return 0
  fi
  local pid
  pid="$(cat "${PID_FILE}")"
  kill -TERM "${pid}" 2>/dev/null || true
  for _ in $(seq 1 20); do
    if ! kill -0 "${pid}" 2>/dev/null; then
      rm -f "${PID_FILE}"
      echo "daemon: stopped"
      return 0
    fi
    sleep 0.2
  done
  if [[ "${FORCE}" -eq 1 ]]; then
    kill -KILL "${pid}" 2>/dev/null || true
    rm -f "${PID_FILE}"
    echo "daemon: force-stopped"
    return 0
  fi
  echo "daemon: stop timeout; use --force" >&2
  return 1
}

status_daemon() {
  clear_stale
  if is_running; then
    echo "daemon: running (pid=$(cat "${PID_FILE}"))"
  else
    echo "daemon: stopped"
  fi
  echo "queue: ${QUEUE_DIR}"
  echo "log: ${LOG_FILE}"
}

show_logs() {
  [[ -f "${LOG_FILE}" ]] || { echo "log file not found: ${LOG_FILE}" >&2; return 1; }
  tail -n "${LINES}" -f "${LOG_FILE}"
}

[[ $# -ge 1 ]] || { usage; exit 2; }
if [[ "$1" == "-h" || "$1" == "--help" ]]; then
  usage
  exit 0
fi
cmd="$1"
shift

while [[ $# -gt 0 ]]; do
  case "$1" in
    --queue-dir)
      QUEUE_DIR="$2"; STATE_DIR="$2"; PID_FILE="${STATE_DIR}/daemon.pid"; shift 2 ;;
    --log)
      LOG_FILE="$2"; shift 2 ;;
    --poll-ms)
      POLL_MS="$2"; shift 2 ;;
    --force)
      FORCE=1; shift ;;
    --lines)
      LINES="$2"; shift 2 ;;
    -h|--help)
      usage; exit 0 ;;
    *)
      echo "Unknown option: $1" >&2; usage; exit 2 ;;
  esac
 done

case "${cmd}" in
  start) start_daemon ;;
  stop) stop_daemon ;;
  restart) stop_daemon || true; start_daemon ;;
  status) status_daemon ;;
  logs) show_logs ;;
  *) echo "Unknown command: ${cmd}" >&2; usage; exit 2 ;;
esac
