#!/bin/zsh
# Routes claude:// URLs (OAuth callbacks, deep links) to the correct profile.
#
# The packaged entry runs plain `claude-desktop %U` with no flags, which
# starts an unflagged default-profile instance that has no keyring backend
# and cannot save the sign-in. This picks the right profile instead.
#
# Ordering:
#   1. A fresh hint written by that profile's xdg-open shim when the app
#      opened the browser -- this is the authoritative signal, and it is
#      consumed on use so it can never misroute a later link.
#   2. Whichever profile is the only one running.
#   3. The most recently started instance, else personal.
#
# Handing the URL to the profile wrapper is safe: Electron's second-instance
# handler forwards it into the running instance with that --user-data-dir.
url="$1"
hint="$HOME/.config/claude-profile-target"
HINT_MAX_AGE=600   # seconds; ignore an abandoned sign-in attempt
running() { pgrep -f -- "--user-data-dir=$HOME/.local/share/claude-$1" >/dev/null 2>&1 }

target=""
if [[ -r "$hint" ]]; then
  age=$(( $(date +%s) - $(stat -c %Y "$hint") ))
  if (( age <= HINT_MAX_AGE )); then
    candidate="$(<"$hint")"
    [[ "$candidate" == (personal|work) ]] && target="$candidate"
  fi
  rm -f "$hint"
fi

if [[ -z "$target" ]]; then
  if running personal && ! running work; then
    target=personal
  elif running work && ! running personal; then
    target=work
  else
    target=$(for p in personal work; do
        pid=$(pgrep -f -- "--user-data-dir=$HOME/.local/share/claude-$p" | head -1)
        [[ -n "$pid" ]] && echo "$(ps -o lstart= -p $pid | xargs -I{} date -d {} +%s) $p"
      done | sort -rn | head -1 | cut -d' ' -f2)
    target="${target:-personal}"
  fi
fi
exec "$HOME/.local/bin/claude-$target" "$url"
