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

if ! command -v bun &>/dev/null; then
  echo "agent-bar: bun is required but not found. Install it: https://bun.sh" >&2
  exit 1
fi

SCRIPT_DIR="$(dirname "$(readlink -f "$0")")"
APP_DIR="$(dirname "$SCRIPT_DIR")"

# Pollution detector: $HOME accidentally got package.json from `bun add` /
# `npm i` without -g. Warns once per hour (per UID) so Waybar logs stay sane.
# Never blocks execution.
agent_bar_check_pollution() {
  local home="${HOME:-}"
  [[ -z "$home" || ! -f "$home/package.json" ]] && return 0
  grep -q '@noctuacore/agent-bar' "$home/package.json" 2>/dev/null || return 0

  local state_dir="${XDG_RUNTIME_DIR:-/tmp}"
  local marker="$state_dir/.agent-bar-pollution-${UID:-0}"
  local now
  now=$(date +%s)
  if [[ -f "$marker" ]]; then
    local last
    last=$(cat "$marker" 2>/dev/null || echo 0)
    [[ $((now - last)) -lt 3600 ]] && return 0
  fi
  echo "$now" > "$marker" 2>/dev/null || true

  if [[ -t 2 ]]; then
    {
      echo ""
      echo "[agent-bar] Detected install pollution in \$HOME (~/package.json)."
      echo "  Run: agent-bar doctor"
      echo ""
    } >&2
  else
    echo "[agent-bar] Pollution detected in \$HOME — run 'agent-bar doctor'." >&2
  fi
}
agent_bar_check_pollution

if [ -f "$APP_DIR/src/index.ts" ]; then
  exec bun "$APP_DIR/src/index.ts" "$@"
fi

if [ -f "$APP_DIR/dist/index.js" ]; then
  exec bun "$APP_DIR/dist/index.js" "$@"
fi

echo "agent-bar: could not find src/index.ts or dist/index.js in $APP_DIR" >&2
exit 1
