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

APP_NAME="KINO Server"
LABEL="ca.dendria.kino.server"
PORT="${KINO_PORT:-8096}"
DATA_DIR="${KINO_DATA_DIR:-$HOME/Library/Application Support/KINO}"
LOG_DIR="$HOME/Library/Logs/KINO"
LOG_FILE="$LOG_DIR/server.log"
PLIST_PATH="$HOME/Library/LaunchAgents/${LABEL}.plist"

# Resolve real script directory (handles symlinks in /usr/local/bin or ~/.local/bin)
SOURCE="${BASH_SOURCE[0]}"
while [ -L "$SOURCE" ]; do
  DIR="$(cd -P "$(dirname "$SOURCE")" >/dev/null 2>&1 && pwd)"
  SOURCE="$(readlink "$SOURCE")"
  [[ "$SOURCE" != /* ]] && SOURCE="$DIR/$SOURCE"
done
BIN_DIR="$(cd -P "$(dirname "$SOURCE")" >/dev/null 2>&1 && pwd)"
INSTALL_ROOT="$(cd "$BIN_DIR/.." && pwd)"

find_node() {
  if [ -n "${KINO_NODE_BIN:-}" ] && [ -x "${KINO_NODE_BIN}" ]; then
    echo "$KINO_NODE_BIN"
    return 0
  fi

  local candidates=(
    "$(command -v node 2>/dev/null || true)"
    "/opt/homebrew/bin/node"
    "/usr/local/bin/node"
  )

  # Check nvm installed versions (prefer Node 22+)
  if [ -d "$HOME/.nvm/versions/node" ]; then
    while IFS= read -r p; do
      candidates+=("$p")
    done < <(ls -1d "$HOME"/.nvm/versions/node/v*/bin/node 2>/dev/null | sort -Vr)
  fi

  for bin in "${candidates[@]}"; do
    [ -z "$bin" ] || [ ! -x "$bin" ] && continue
    local major
    major="$("$bin" -p "Number(process.versions.node.split('.')[0])" 2>/dev/null || echo 0)"
    if [ "$major" -ge 22 ]; then
      echo "$bin"
      return 0
    fi
  done

  return 1
}

get_lan_ip() {
  local ip=""
  if command -v ipconfig >/dev/null 2>&1; then
    ip="$(ipconfig getifaddr en0 2>/dev/null || ipconfig getifaddr en1 2>/dev/null || true)"
  fi
  if [ -z "$ip" ]; then
    ip="localhost"
  fi
  echo "$ip"
}

write_plist() {
  local node_bin="$1"
  mkdir -p "$HOME/Library/LaunchAgents" "$LOG_DIR" "$DATA_DIR"
  cat > "$PLIST_PATH" <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>${LABEL}</string>
  <key>ProgramArguments</key>
  <array>
    <string>${node_bin}</string>
    <string>${INSTALL_ROOT}/server/dist/index.js</string>
  </array>
  <key>WorkingDirectory</key>
  <string>${INSTALL_ROOT}</string>
  <key>EnvironmentVariables</key>
  <dict>
    <key>KINO_DATA_DIR</key>
    <string>${DATA_DIR}</string>
    <key>KINO_PORT</key>
    <string>${PORT}</string>
    <key>PATH</key>
    <string>/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin</string>
  </dict>
  <key>RunAtLoad</key>
  <true/>
  <key>KeepAlive</key>
  <true/>
  <key>StandardOutPath</key>
  <string>${LOG_FILE}</string>
  <key>StandardErrorPath</key>
  <string>${LOG_FILE}</string>
</dict>
</plist>
EOF
}

cmd="${1:-status}"

case "$cmd" in
  run)
    NODE_BIN="$(find_node)" || {
      echo "Error: Node.js 22+ is required to run KINO Server (install via 'brew install node' or https://nodejs.org)." >&2
      exit 1
    }
    mkdir -p "$DATA_DIR"
    export KINO_DATA_DIR="$DATA_DIR"
    export KINO_PORT="$PORT"
    export PATH="/opt/homebrew/bin:/usr/local/bin:$PATH"
    cd "$INSTALL_ROOT"
    exec "$NODE_BIN" "$INSTALL_ROOT/server/dist/index.js"
    ;;

  start)
    NODE_BIN="$(find_node)" || {
      echo "Error: Node.js 22+ is required. Install with: brew install node" >&2
      exit 1
    }
    write_plist "$NODE_BIN"
    launchctl bootout "gui/$(id -u)/${LABEL}" >/dev/null 2>&1 || true
    launchctl bootstrap "gui/$(id -u)" "$PLIST_PATH"
    sleep 1
    LAN_IP="$(get_lan_ip)"
    echo "${APP_NAME} started."
    echo "  Local:   http://localhost:${PORT}"
    echo "  Network: http://${LAN_IP}:${PORT}"
    echo "  Logs:    ${LOG_FILE}"
    ;;

  stop)
    launchctl bootout "gui/$(id -u)/${LABEL}" >/dev/null 2>&1 || true
    echo "${APP_NAME} stopped."
    ;;

  restart)
    "$0" stop
    "$0" start
    ;;

  status)
    if curl -fsS "http://127.0.0.1:${PORT}/api/ping" >/dev/null 2>&1; then
      LAN_IP="$(get_lan_ip)"
      echo "${APP_NAME} is running."
      echo "  Local:   http://localhost:${PORT}"
      echo "  Network: http://${LAN_IP}:${PORT}"
      echo "  Data:    ${DATA_DIR}"
    else
      echo "${APP_NAME} is not running. Start it with: kino-server start"
      exit 1
    fi
    ;;

  logs)
    mkdir -p "$LOG_DIR"
    touch "$LOG_FILE"
    tail -n 80 -f "$LOG_FILE"
    ;;

  open)
    open "http://localhost:${PORT}"
    ;;

  uninstall)
    launchctl bootout "gui/$(id -u)/${LABEL}" >/dev/null 2>&1 || true
    rm -f "$PLIST_PATH"
    echo "LaunchAgent removed. Your library database remains at: ${DATA_DIR}"
    echo "To remove binaries as well, delete ${INSTALL_ROOT}."
    ;;

  *)
    echo "Usage: kino-server {start|stop|restart|status|logs|open|run|uninstall}"
    exit 1
    ;;
esac
