#!/usr/bin/env bash
# keepalive — keepalive management CLI
#
# Commands:
#   start, stop, restart, status, logs, attach, detach, workload,
#   doctor, service, install, uninstall, version, help.

set -u

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" 2>/dev/null && pwd)" || SCRIPT_DIR=""

keepalive_find_common() {
  local c
  for c in \
    "${KEEPALIVE_LIB_DIR:+${KEEPALIVE_LIB_DIR}/keepalive-common.sh}" \
    "${SCRIPT_DIR:+${SCRIPT_DIR}/lib/keepalive-common.sh}" \
    "${HOME:+${HOME}/.local/lib/keepalive/keepalive-common.sh}" \
    "/usr/lib/keepalive/keepalive-common.sh"
  do
    if [ -n "$c" ] && [ -r "$c" ]; then
      printf '%s' "$c"
      return 0
    fi
  done
  return 1
}

COMMON_LIB="$(keepalive_find_common)" || {
  printf 'keepalive: cannot locate keepalive-common.sh\n' >&2
  exit 1
}
# shellcheck disable=SC1090
. "$COMMON_LIB"

keepalive_load_config

BIN_DIR="${KEEPALIVE_BIN_DIR:-$KEEPALIVE_BIN_HOME}"
STATE_DIR="$KEEPALIVE_STATE_DIR"
LOG_FILE="$KEEPALIVE_LOG_FILE"
TMUX_SESSION="$KEEPALIVE_SESSION"

ensure_state_dir() {
  mkdir -p "$STATE_DIR" 2>/dev/null || {
    printf 'keepalive: cannot create state directory: %s\n' "$STATE_DIR" >&2
    return 1
  }
  if [ ! -w "$STATE_DIR" ]; then
    printf 'keepalive: state directory is not writable: %s\n' "$STATE_DIR" >&2
    return 1
  fi
  return 0
}

ensure_log_file() {
  ensure_state_dir || return 1
  if [ -e "$LOG_FILE" ]; then
    if [ ! -w "$LOG_FILE" ]; then
      printf 'keepalive: log file is not writable: %s\n' "$LOG_FILE" >&2
      return 1
    fi
  else
    touch "$LOG_FILE" 2>/dev/null || {
      printf 'keepalive: cannot create log file: %s\n' "$LOG_FILE" >&2
      return 1
    }
  fi
  return 0
}

check_tmux() {
  if ! command -v tmux >/dev/null 2>&1; then
    printf 'keepalive: tmux is required but was not found in PATH\n' >&2
    printf 'Install tmux: sudo apt install tmux (Debian/Ubuntu)\n' >&2
    return 1
  fi
  return 0
}

resolve_heartbeat_bin() {
  keepalive_resolve_bin "keepalive-heartbeat" "$SCRIPT_DIR"
}

resolve_workload_bin() {
  keepalive_resolve_bin "keepalive-workload" "$SCRIPT_DIR"
}

# Inspect tmux session + pane process liveness accurately.
# Outputs one of: tmux_unavailable, tmux_none, tmux_stale, tmux_alive
tmux_session_state() {
  if ! command -v tmux >/dev/null 2>&1; then
    echo "tmux_unavailable"
    return 0
  fi

  if ! tmux has-session -t "$TMUX_SESSION" 2>/dev/null; then
    echo "tmux_none"
    return 0
  fi

  local pane_dead pane_pid pid_file saved_pid proc_args
  pane_dead="$(tmux list-panes -t "$TMUX_SESSION" -F '#{pane_dead}' 2>/dev/null | head -n1)"
  if [ "$pane_dead" = "1" ]; then
    echo "tmux_stale"
    return 0
  fi

  pane_pid="$(tmux list-panes -t "$TMUX_SESSION" -F '#{pane_pid}' 2>/dev/null | head -n1)"
  if [ -n "$pane_pid" ] && kill -0 "$pane_pid" 2>/dev/null; then
    if command -v ps >/dev/null 2>&1; then
      proc_args="$(ps -p "$pane_pid" -o args= 2>/dev/null || true)"
      case "$proc_args" in
        *keepalive-heartbeat*)
          echo "tmux_alive"
          return 0
          ;;
      esac
    else
      echo "tmux_alive"
      return 0
    fi
  fi

  pid_file="${STATE_DIR}/tmux-${TMUX_SESSION}.pid"
  if [ -f "$pid_file" ]; then
    saved_pid="$(cat "$pid_file" 2>/dev/null || true)"
    if [ -n "$saved_pid" ] && kill -0 "$saved_pid" 2>/dev/null; then
      echo "tmux_alive"
      return 0
    fi
  fi

  echo "tmux_stale"
  return 0
}

systemd_user_available() {
  command -v systemctl >/dev/null 2>&1 && systemctl --user status >/dev/null 2>&1
}

systemd_service_active() {
  command -v systemctl >/dev/null 2>&1 && systemctl --user is-active --quiet keepalive.service 2>/dev/null
}

cmd_start() {
  keepalive_validate_config || return 1
  check_tmux || return 1

  if systemd_service_active; then
    printf 'keepalive: systemd user service "keepalive.service" is already active.\n' >&2
    printf 'Stop it first ("keepalive service stop") to avoid duplicate instances.\n' >&2
    return 1
  fi

  local session_state
  session_state="$(tmux_session_state)"

  if [ "$session_state" = "tmux_alive" ]; then
    printf 'keepalive: heartbeat is already running in tmux session "%s"\n' "$TMUX_SESSION"
    printf 'Use "keepalive status" to inspect or "keepalive stop" to stop it.\n' >&2
    return 1
  fi

  if [ "$session_state" = "tmux_stale" ]; then
    printf 'keepalive: cleaning up stale tmux session "%s"\n' "$TMUX_SESSION"
    tmux kill-session -t "$TMUX_SESSION" 2>/dev/null || true
    rm -f "${STATE_DIR}/tmux-${TMUX_SESSION}.pid" "${STATE_DIR}/tmux-${TMUX_SESSION}.session_pid" 2>/dev/null || true
  fi

  ensure_log_file || return 1

  local hb_bin wl_bin
  hb_bin="$(resolve_heartbeat_bin)" || {
    printf 'keepalive: keepalive-heartbeat not found. Run "keepalive install" first.\n' >&2
    return 1
  }
  if [ "$KEEPALIVE_CMD" = "workload" ]; then
    wl_bin="$(resolve_workload_bin)" || {
      printf 'keepalive: keepalive-workload not found. Run "keepalive install" first.\n' >&2
      return 1
    }
  fi

  local lib_dir
  lib_dir="$(cd "$(dirname "$COMMON_LIB")" 2>/dev/null && pwd)"

  # Build a safely quoted shell command for tmux (prevents shell injection).
  local launch_cmd
  printf -v launch_cmd \
    'env KEEPALIVE_INTERVAL=%q KEEPALIVE_BEATS=%q KEEPALIVE_CMD=%q KEEPALIVE_CMD_TIMEOUT=%q KEEPALIVE_WORKLOAD_MB=%q KEEPALIVE_WORKLOAD_SECONDS=%q KEEPALIVE_PING_URL=%q KEEPALIVE_PING_GATEWAY=%q KEEPALIVE_SESSION=%q KEEPALIVE_LOG_LEVEL=%q KEEPALIVE_LOG_MAX_BYTES=%q KEEPALIVE_STATE_DIR=%q KEEPALIVE_BIN_DIR=%q KEEPALIVE_LIB_DIR=%q %q' \
    "$KEEPALIVE_INTERVAL" \
    "$KEEPALIVE_BEATS" \
    "$KEEPALIVE_CMD" \
    "$KEEPALIVE_CMD_TIMEOUT" \
    "$KEEPALIVE_WORKLOAD_MB" \
    "$KEEPALIVE_WORKLOAD_SECONDS" \
    "$KEEPALIVE_PING_URL" \
    "$KEEPALIVE_PING_GATEWAY" \
    "$TMUX_SESSION" \
    "$KEEPALIVE_LOG_LEVEL" \
    "$KEEPALIVE_LOG_MAX_BYTES" \
    "$STATE_DIR" \
    "$(dirname "$hb_bin")" \
    "$lib_dir" \
    "$hb_bin"

  if ! tmux new-session -d -s "$TMUX_SESSION" "$launch_cmd"; then
    printf 'keepalive: failed to create tmux session "%s"\n' "$TMUX_SESSION" >&2
    return 1
  fi

  sleep 0.4
  local heartbeat_pid tmux_pid
  heartbeat_pid="$(tmux list-panes -t "$TMUX_SESSION" -F '#{pane_pid}' 2>/dev/null | head -n1)"
  if [ -n "$heartbeat_pid" ]; then
    printf '%s\n' "$heartbeat_pid" > "${STATE_DIR}/tmux-${TMUX_SESSION}.pid" 2>/dev/null || true
  fi
  tmux_pid="$(tmux display-message -p '#{session_pid}' -t "$TMUX_SESSION" 2>/dev/null || true)"
  if [ -n "$tmux_pid" ]; then
    printf '%s\n' "$tmux_pid" > "${STATE_DIR}/tmux-${TMUX_SESSION}.session_pid" 2>/dev/null || true
  fi

  keepalive_banner
  printf 'keepalive: heartbeat started in tmux session "%s" (interval=%ss, beats=%s, mode=%s)\n' \
    "$TMUX_SESSION" "$KEEPALIVE_INTERVAL" "$KEEPALIVE_BEATS" "$KEEPALIVE_CMD"
  printf 'Use "keepalive status" to check, "keepalive logs" to inspect, "keepalive attach" to view.\n'
}

cmd_stop() {
  if ! check_tmux; then
    return 1
  fi

  local session_state
  session_state="$(tmux_session_state)"

  if [ "$session_state" = "tmux_none" ] || [ "$session_state" = "tmux_unavailable" ]; then
    rm -f "${STATE_DIR}/tmux-${TMUX_SESSION}.pid" "${STATE_DIR}/tmux-${TMUX_SESSION}.session_pid" 2>/dev/null || true
    printf 'keepalive: no tmux session "%s" found (already stopped)\n' "$TMUX_SESSION"
    return 0
  fi

  local pane_pid
  pane_pid="$(tmux list-panes -t "$TMUX_SESSION" -F '#{pane_pid}' 2>/dev/null | head -n1)"
  if [ -n "$pane_pid" ] && kill -0 "$pane_pid" 2>/dev/null; then
    kill -TERM "$pane_pid" 2>/dev/null || true
    sleep 0.3
  fi

  tmux kill-session -t "$TMUX_SESSION" 2>/dev/null || true
  rm -f "${STATE_DIR}/tmux-${TMUX_SESSION}.pid" "${STATE_DIR}/tmux-${TMUX_SESSION}.session_pid" 2>/dev/null || true

  if [ "$session_state" = "tmux_stale" ]; then
    printf 'keepalive: cleaned up stale tmux session "%s"\n' "$TMUX_SESSION"
  else
    printf 'keepalive: stopped heartbeat (tmux session "%s")\n' "$TMUX_SESSION"
  fi
  return 0
}

cmd_restart() {
  cmd_stop || return 1
  sleep 0.3
  cmd_start
}

cmd_status() {
  local session_state hb_bin pane_pid last_log step
  session_state="$(tmux_session_state)"
  step=$(( KEEPALIVE_INTERVAL / KEEPALIVE_BEATS ))
  [ "$step" -lt 1 ] && step=1

  printf 'Keepalive Status (v%s)\n' "$KEEPALIVE_VERSION"
  printf '  Session name  : %s\n' "$TMUX_SESSION"
  printf '  Interval      : %ss (%s beat(s)/window, every %ss)\n' "$KEEPALIVE_INTERVAL" "$KEEPALIVE_BEATS" "$step"
  printf '  Workload mode : %s\n' "$KEEPALIVE_CMD"
  printf '  Log file      : %s\n' "$LOG_FILE"

  if [ -r "$KEEPALIVE_USER_CONFIG" ]; then
    printf '  User config   : %s\n' "$KEEPALIVE_USER_CONFIG"
  fi
  if [ -r "$KEEPALIVE_SYSTEM_CONFIG" ]; then
    printf '  System config : %s\n' "$KEEPALIVE_SYSTEM_CONFIG"
  fi

  if hb_bin="$(resolve_heartbeat_bin 2>/dev/null)"; then
    printf '  Heartbeat bin : %s\n' "$hb_bin"
  else
    printf '  Heartbeat bin : MISSING (run "keepalive install")\n'
  fi

  if systemd_service_active; then
    printf '  Systemd unit  : active (keepalive.service)\n'
  fi

  case "$session_state" in
    tmux_unavailable)
      printf '  State         : STOPPED (tmux not installed)\n'
      return 1
      ;;
    tmux_none)
      if systemd_service_active; then
        printf '  State         : RUNNING (via systemd user service)\n'
      else
        printf '  State         : STOPPED (no tmux session "%s")\n' "$TMUX_SESSION"
      fi
      ;;
    tmux_stale)
      printf '  State         : STALE (tmux session "%s" exists, heartbeat process is dead)\n' "$TMUX_SESSION"
      printf '  Action        : Run "keepalive restart" to recover.\n'
      return 1
      ;;
    tmux_alive)
      pane_pid="$(tmux list-panes -t "$TMUX_SESSION" -F '#{pane_pid}' 2>/dev/null | head -n1)"
      printf '  State         : RUNNING (tmux session "%s", PID %s)\n' "$TMUX_SESSION" "${pane_pid:-unknown}"
      ;;
  esac

  if [ -f "$LOG_FILE" ]; then
    last_log="$(tail -n1 "$LOG_FILE" 2>/dev/null || true)"
    if [ -n "$last_log" ]; then
      printf '  Last log      : %s\n' "$last_log"
    else
      printf '  Last log      : (empty)\n'
    fi
  else
    printf '  Last log      : (no log file yet)\n'
  fi

  if ! keepalive_validate_config 2>/dev/null; then
    printf '  Warning       : Current configuration has validation errors; run "keepalive doctor".\n'
  fi

  printf '\nNOTE: Running locally only generates activity inside the host; it cannot\n'
  printf 'guarantee that a VPS provider will not suspend or terminate the instance.\n'
  return 0
}

cmd_logs() {
  local follow=false
  local line_count=50

  while [ $# -gt 0 ]; do
    case "$1" in
      -f|--follow)
        follow=true
        shift
        ;;
      --help|-h)
        printf 'Usage: keepalive logs [-f] [N]\n'
        return 0
        ;;
      *)
        case "$1" in
          ''|*[!0-9]*)
            printf 'keepalive: invalid line count: %s\n' "$1" >&2
            return 1
            ;;
          *)
            if [ "$1" -lt 1 ]; then
              printf 'keepalive: line count must be at least 1\n' >&2
              return 1
            fi
            line_count="$1"
            shift
            ;;
        esac
        ;;
    esac
  done

  if [ ! -f "$LOG_FILE" ]; then
    printf 'keepalive: no log file found at %s\n' "$LOG_FILE" >&2
    return 1
  fi

  if [ "$follow" = true ]; then
    tail -n "$line_count" -f "$LOG_FILE"
  else
    tail -n "$line_count" "$LOG_FILE"
  fi
}

cmd_attach() {
  check_tmux || return 1
  if ! tmux has-session -t "$TMUX_SESSION" 2>/dev/null; then
    printf 'keepalive: no tmux session "%s" found. Run "keepalive start" first.\n' "$TMUX_SESSION" >&2
    return 1
  fi
  tmux attach-session -t "$TMUX_SESSION"
}

cmd_detach() {
  check_tmux || return 1
  if ! tmux has-session -t "$TMUX_SESSION" 2>/dev/null; then
    printf 'keepalive: no tmux session "%s" found.\n' "$TMUX_SESSION" >&2
    return 1
  fi
  tmux detach-client -s "$TMUX_SESSION" 2>/dev/null || true
  printf 'keepalive: detached clients from tmux session "%s"\n' "$TMUX_SESSION"
}

cmd_workload() {
  keepalive_validate_config || return 1
  ensure_state_dir || return 1

  local wl_bin
  wl_bin="$(resolve_workload_bin)" || {
    printf 'keepalive: keepalive-workload not found. Run "keepalive install" first.\n' >&2
    return 1
  }

  KEEPALIVE_WORKLOAD_MB="$KEEPALIVE_WORKLOAD_MB" \
  KEEPALIVE_WORKLOAD_SECONDS="$KEEPALIVE_WORKLOAD_SECONDS" \
  KEEPALIVE_STATE_DIR="$STATE_DIR" \
    "$wl_bin"
}

cmd_doctor() {
  local issues=0 warn=0 tool hb_bin wl_bin session_state

  printf 'Keepalive Diagnostics (v%s)\n\n' "$KEEPALIVE_VERSION"

  # 1. Bash version
  printf '[check] Bash version: %s\n' "${BASH_VERSION:-unknown}"
  if [ "${BASH_VERSINFO[0]:-0}" -lt 4 ]; then
    printf '  [FAIL] Bash 4+ is required\n'
    issues=$((issues + 1))
  else
    printf '  [OK]   Bash 4+ supported\n'
  fi

  # 2. Config validation
  printf '[check] Configuration\n'
  if keepalive_validate_config; then
    printf '  [OK]   Configuration valid (interval=%ss, beats=%s, mode=%s)\n' \
      "$KEEPALIVE_INTERVAL" "$KEEPALIVE_BEATS" "$KEEPALIVE_CMD"
  else
    printf '  [FAIL] Configuration validation failed\n'
    issues=$((issues + 1))
  fi

  # 3. Installation integrity
  printf '[check] Installation integrity\n'
  if hb_bin="$(resolve_heartbeat_bin 2>/dev/null)"; then
    printf '  [OK]   keepalive-heartbeat: %s\n' "$hb_bin"
  else
    printf '  [FAIL] keepalive-heartbeat not found\n'
    issues=$((issues + 1))
  fi
  if wl_bin="$(resolve_workload_bin 2>/dev/null)"; then
    printf '  [OK]   keepalive-workload: %s\n' "$wl_bin"
  else
    printf '  [FAIL] keepalive-workload not found\n'
    issues=$((issues + 1))
  fi

  # 4. Dependencies
  printf '[check] Dependencies\n'
  for tool in dd gzip sha256sum; do
    if command -v "$tool" >/dev/null 2>&1; then
      printf '  [OK]   %s (%s)\n' "$tool" "$(command -v "$tool")"
    else
      printf '  [FAIL] %s missing (required for workload)\n' "$tool"
      issues=$((issues + 1))
    fi
  done

  if command -v tmux >/dev/null 2>&1; then
    printf '  [OK]   tmux (%s)\n' "$(tmux -V 2>/dev/null || echo present)"
  else
    printf '  [WARN] tmux not installed (required for tmux persistence)\n'
    warn=$((warn + 1))
  fi

  for tool in flock timeout curl wget ip ping systemctl; do
    if command -v "$tool" >/dev/null 2>&1; then
      printf '  [OK]   %s (optional)\n' "$tool"
    else
      printf '  [INFO] %s not installed (optional)\n' "$tool"
    fi
  done

  # 5. State directory & permissions
  printf '[check] State & permissions\n'
  if [ -d "$STATE_DIR" ]; then
    if [ -w "$STATE_DIR" ]; then
      printf '  [OK]   State dir writable: %s\n' "$STATE_DIR"
    else
      printf '  [FAIL] State dir not writable: %s\n' "$STATE_DIR"
      issues=$((issues + 1))
    fi
  else
    printf '  [INFO] State dir not created yet: %s\n' "$STATE_DIR"
  fi

  # 6. Process / session state
  printf '[check] Session state\n'
  session_state="$(tmux_session_state)"
  printf '  [INFO] tmux state: %s\n' "$session_state"
  if [ "$session_state" = "tmux_stale" ]; then
    printf '  [WARN] Stale tmux session detected; run "keepalive restart" or "keepalive stop"\n'
    warn=$((warn + 1))
  fi

  printf '\nSummary: %d error(s), %d warning(s)\n' "$issues" "$warn"
  [ "$issues" -eq 0 ]
}

cmd_service() {
  local sub="${1:-status}"
  local unit_dir="${XDG_CONFIG_HOME:-${KEEPALIVE_USER_HOME}/.config}/systemd/user"
  local unit_file="${unit_dir}/keepalive.service"
  local hb_bin lib_dir

  if ! command -v systemctl >/dev/null 2>&1; then
    printf 'keepalive: systemctl is not installed on this system.\n' >&2
    return 1
  fi

  case "$sub" in
    install)
      hb_bin="$(resolve_heartbeat_bin)" || {
        printf 'keepalive: keepalive-heartbeat not found. Install keepalive first.\n' >&2
        return 1
      }
      lib_dir="$(cd "$(dirname "$COMMON_LIB")" 2>/dev/null && pwd)"
      mkdir -p "$unit_dir" || return 1
      cat > "$unit_file" <<EOF
[Unit]
Description=Keepalive VPS Heartbeat Service
After=network-online.target

[Service]
Type=simple
Environment=KEEPALIVE_LIB_DIR=${lib_dir}
Environment=KEEPALIVE_STATE_DIR=${STATE_DIR}
ExecStart=${hb_bin}
Restart=on-failure
RestartSec=10

[Install]
WantedBy=default.target
EOF
      systemctl --user daemon-reload
      systemctl --user enable keepalive.service
      printf 'keepalive: installed user service at %s\n' "$unit_file"
      printf 'Start with: keepalive service start\n'
      ;;
    start)
      if [ "$(tmux_session_state)" = "tmux_alive" ]; then
        printf 'keepalive: tmux session "%s" is running. Stop it ("keepalive stop") before starting systemd service.\n' "$TMUX_SESSION" >&2
        return 1
      fi
      systemctl --user start keepalive.service
      printf 'keepalive: systemd user service started\n'
      ;;
    stop)
      systemctl --user stop keepalive.service
      printf 'keepalive: systemd user service stopped\n'
      ;;
    status)
      systemctl --user status keepalive.service --no-pager
      ;;
    uninstall)
      systemctl --user stop keepalive.service 2>/dev/null || true
      systemctl --user disable keepalive.service 2>/dev/null || true
      rm -f "$unit_file"
      systemctl --user daemon-reload 2>/dev/null || true
      printf 'keepalive: removed systemd user service\n'
      ;;
    *)
      printf 'Usage: keepalive service <install|start|stop|status|uninstall>\n' >&2
      return 1
      ;;
  esac
}

cmd_install() {
  local installer=""
  if [ -x "${SCRIPT_DIR}/../install.sh" ]; then
    installer="${SCRIPT_DIR}/../install.sh"
  elif [ -x "${SCRIPT_DIR}/install.sh" ]; then
    installer="${SCRIPT_DIR}/install.sh"
  fi

  if [ -n "$installer" ]; then
    exec "$installer" "$@"
  fi

  # Fallback remote install when invoked standalone
  local repo="https://raw.githubusercontent.com/ayusharyaneth/keepalive/main"
  local bin_dir="$BIN_DIR"
  local lib_dir="$KEEPALIVE_LIB_HOME"
  local start=false

  while [ $# -gt 0 ]; do
    case "$1" in
      --repo)   repo="${2:?missing repo URL}"; shift 2 ;;
      --start)  start=true; shift ;;
      --help|-h)
        printf 'Usage: keepalive install [--repo URL] [--start]\n'
        return 0
        ;;
      *)
        printf 'keepalive: unknown flag: %s\n' "$1" >&2
        return 1
        ;;
    esac
  done

  mkdir -p "$bin_dir" "$lib_dir" "$STATE_DIR" || return 1

  download_file() {
    local url="$1" dest="$2"
    if command -v curl >/dev/null 2>&1; then
      curl -fsSL "$url" -o "$dest"
    elif command -v wget >/dev/null 2>&1; then
      wget -q "$url" -O "$dest"
    else
      printf 'keepalive: curl or wget is required for remote install\n' >&2
      return 1
    fi
  }

  download_file "${repo}/keepalive/lib/keepalive-common.sh" "${lib_dir}/keepalive-common.sh" || return 1
  download_file "${repo}/keepalive/heartbeat/keepalive-heartbeat" "${bin_dir}/keepalive-heartbeat" || return 1
  download_file "${repo}/keepalive/workload/keepalive-workload" "${bin_dir}/keepalive-workload" || return 1
  chmod 755 "${bin_dir}/keepalive-heartbeat" "${bin_dir}/keepalive-workload"
  chmod 644 "${lib_dir}/keepalive-common.sh"

  ensure_log_file || return 1
  keepalive_banner
  printf 'keepalive: installation complete (%s)\n' "$bin_dir"
  if [ "$start" = true ]; then
    cmd_start
  fi
}

cmd_uninstall() {
  local purge=false
  local yes=false

  while [ $# -gt 0 ]; do
    case "$1" in
      --purge|-p) purge=true; shift ;;
      --yes|-y)   yes=true; shift ;;
      --help|-h)
        printf 'Usage: keepalive uninstall [--purge|-p] [--yes|-y]\n'
        return 0
        ;;
      *)
        printf 'keepalive: unknown flag: %s\n' "$1" >&2
        return 1
        ;;
    esac
  done

  if [ "$purge" = true ] && [ "$yes" = false ] && [ -t 0 ]; then
    local reply
    printf 'This will delete logs and state in %s. Continue? [y/N] ' "$STATE_DIR"
    read -r reply
    case "$reply" in
      y|Y|yes|YES) ;;
      *)
        printf 'keepalive: uninstall aborted\n'
        return 1
        ;;
    esac
  fi

  if command -v tmux >/dev/null 2>&1; then
    cmd_stop >/dev/null 2>&1 || true
  fi
  if systemd_service_active; then
    systemctl --user stop keepalive.service 2>/dev/null || true
  fi

  # Warn if installed via dpkg/apt
  if [ -x "/usr/bin/keepalive-heartbeat" ] && command -v dpkg >/dev/null 2>&1 && dpkg -S /usr/bin/keepalive-heartbeat >/dev/null 2>&1; then
    printf 'keepalive: system package detected. Remove it with: sudo apt remove keepalive\n'
  else
    rm -f "${BIN_DIR}/keepalive-heartbeat" "${BIN_DIR}/keepalive-workload" "${BIN_DIR}/keepalive" 2>/dev/null || true
    rm -rf "$KEEPALIVE_LIB_HOME" 2>/dev/null || true
  fi

  if [ "$purge" = true ]; then
    rm -rf "$STATE_DIR" "$KEEPALIVE_CONFIG_HOME" 2>/dev/null || true
    printf 'keepalive: removed user state and configuration\n'
  else
    rm -f "${STATE_DIR}/tmux-${TMUX_SESSION}.pid" "${STATE_DIR}/tmux-${TMUX_SESSION}.session_pid" "${STATE_DIR}/keepalive-${TMUX_SESSION}.lock" 2>/dev/null || true
    printf 'keepalive: uninstall complete (logs and configuration preserved)\n'
  fi
}

cmd_version() {
  printf 'keepalive version %s (%s/%s)\n' "$KEEPALIVE_VERSION" "$(uname -s 2>/dev/null || echo unknown)" "$(uname -m 2>/dev/null || echo unknown)"
}

cmd_help() {
  cat <<'EOF'
keepalive - lightweight VPS keep-alive heartbeat utility

Usage: keepalive <command> [options]

Commands:
  start                Start the heartbeat in a detached tmux session
  stop                 Stop the running heartbeat and clean up session
  restart              Restart the heartbeat (stop + start)
  status               Show session, process, config, and last log status
  logs [-f] [N]        Show last N log lines (default 50) or follow with -f
  attach               Attach to the running tmux session
  detach               Detach clients from the tmux session
  workload             Run one bounded CPU+disk workload burst immediately
  doctor               Run read-only diagnostics on dependencies and config
  service <action>     Manage optional systemd user service (install|start|stop|status|uninstall)
  install [options]    Install keepalive scripts
  uninstall [--purge]  Remove user-installed keepalive files (--purge deletes logs/config)
  version              Show keepalive version
  help                 Show this help message

Configuration (KEEPALIVE_ prefix, or ~/.config/keepalive/keepalive.conf):
  KEEPALIVE_INTERVAL         Seconds per window (default: 600; 1200 for vmstat)
  KEEPALIVE_BEATS            Beats per window (default: 1)
  KEEPALIVE_CMD              Command per beat (default: workload)
  KEEPALIVE_CMD_TIMEOUT      Max seconds per beat command (default: 120)
  KEEPALIVE_WORKLOAD_MB      MiB per workload burst (default: 16, range: 1-512)
  KEEPALIVE_WORKLOAD_SECONDS Minimum seconds per burst (default: 3, range: 0-60)
  KEEPALIVE_PING_URL         Optional HTTP(S) URL per beat
  KEEPALIVE_PING_GATEWAY     Ping default gateway per beat: 0 or 1 (default: 0)
  KEEPALIVE_SESSION          tmux session name (default: keepalive)
  KEEPALIVE_LOG_LEVEL        DEBUG, INFO, WARN, or ERROR (default: INFO)
  KEEPALIVE_LOG_MAX_BYTES    Log rotation threshold in bytes (default: 1048576)
EOF
}

main() {
  local command="${1:-help}"
  shift || true

  case "$command" in
    start)       cmd_start "$@" ;;
    stop)        cmd_stop "$@" ;;
    restart)     cmd_restart "$@" ;;
    status)      cmd_status "$@" ;;
    logs)        cmd_logs "$@" ;;
    attach)      cmd_attach "$@" ;;
    detach)      cmd_detach "$@" ;;
    workload)    cmd_workload "$@" ;;
    doctor)      cmd_doctor "$@" ;;
    service)     cmd_service "$@" ;;
    install)     cmd_install "$@" ;;
    uninstall)   cmd_uninstall "$@" ;;
    version|--version|-v) cmd_version ;;
    help|--help|-h)       cmd_help ;;
    *)
      printf 'keepalive: unknown command "%s"\n\n' "$command" >&2
      cmd_help >&2
      return 1
      ;;
  esac
}

main "$@"
