#!/bin/bash
#
# Purpose : Claude Code's Notification and Stop hooks (see claude.sh): a desktop
#           notification that, when clicked, brings you back to the app Claude
#           is running in (Console, VS Codium, ...).
#
# claude-notify <text>, with the hook's JSON on stdin. <text> is shown when
# the JSON has no message of its own, as with Stop.
#
# GNOME brings an app forward when its notification is clicked only if it
# knows which app sent it. notify-send runs from Claude, not from the app, so
# the notification names the app itself in its desktop-entry hint: the first
# terminal or editor found among the processes Claude runs under. Clicking
# brings forward that app's most recently used window.
#
# CLAUDE_NOTIFY_PROC (default /proc) and CLAUDE_NOTIFY_PID (default this
# script's parent) are for the tests.

text="${1:-Needs your input}"
proc="${CLAUDE_NOTIFY_PROC:-/proc}"

input=""
[ -t 0 ] || input="$(cat)"
message="$(jq -r '.message // empty' <<< "$input" 2> /dev/null)"
cwd="$(jq -r '.cwd // empty' <<< "$input" 2> /dev/null)"
[ -n "$cwd" ] || cwd="$PWD"

# The desktop entries an app may have, by the name of its process
entries_for() {
  case "$1" in
    kgx) echo org.gnome.Console ;;
    ptyxis | ptyxis-agent) echo org.gnome.Ptyxis ;;
    gnome-terminal*) echo org.gnome.Terminal ;;
    ghostty) echo com.mitchellh.ghostty ;;
    kitty) echo kitty ;;
    alacritty) echo Alacritty ;;
    wezterm-gui) echo org.wezfurlong.wezterm ;;
    cosmic-term) echo com.system76.CosmicTerm ;;
    codium) echo com.vscodium.codium codium vscodium ;;
    code | code-oss) echo code com.visualstudio.code code-oss ;;
  esac
}

installed() {
  local dir
  local IFS=:
  for dir in "${XDG_DATA_HOME:-$HOME/.local/share}" ${XDG_DATA_DIRS:-/usr/local/share:/usr/share}; do
    [ -f "$dir/applications/$1.desktop" ] && return 0
  done
  return 1
}

find_entry() {
  # Inside a Flatpak (VS Codium's, say), the app is the Flatpak
  if [ -n "$FLATPAK_ID" ]; then
    echo "$FLATPAK_ID"
    return
  fi

  # tmux's server doesn't run under the terminal, its client does
  local pid="${CLAUDE_NOTIFY_PID:-$PPID}"
  if [ -n "$TMUX" ]; then
    pid="$(tmux display-message -p '#{client_pid}' 2> /dev/null)" || return
  fi

  local comm entry hops=0
  while [ -n "$pid" ] && [ "$pid" -gt 1 ] && [ "$hops" -lt 30 ]; do
    comm="$(cat "$proc/$pid/comm" 2> /dev/null)" || return
    for entry in $(entries_for "$comm"); do
      if installed "$entry"; then
        echo "$entry"
        return
      fi
    done
    pid="$(awk '/^PPid:/ { print $2 }' "$proc/$pid/status" 2> /dev/null)"
    hops=$((hops + 1))
  done
}

args=(--app-name="Claude Code" --icon=dialog-information)
entry="$(find_entry)"
[ -n "$entry" ] && args+=(--hint="string:desktop-entry:$entry")

exec notify-send "${args[@]}" "Claude Code: ${cwd##*/}" "${message:-$text}"
