#!/usr/bin/env bash

# omarchy:summary=Focus a window by application identity
# omarchy:args=<app-name>
# omarchy:examples=omarchy focus app Slack

case $("${BASH_SOURCE[0]%/*}/omarchy-compositor") in
  hyprland) exec "${BASH_SOURCE[0]%/*}/omarchy-hyprland-focus-app" "$@" ;;
  sway) ;;
  *) exit 0 ;;
esac

usage() {
  echo "Usage: omarchy-focus-app <app-name>" >&2
  exit 1
}

app=${1:-}
[[ -n $app ]] || usage

# The Hyprland helper's match on sway: a Wayland client's app_id or an Xwayland
# client's class first, then an agent terminal by its title, since those share
# the org.omarchy.agent app_id.
id=$(
  swaymsg -t get_tree -r 2>/dev/null |
    jq -r --arg pattern "$app" \
      'def matches($value): ($value // "") | test($pattern; "i");
       first(
         (.. | objects | select(.pid != null) | select(matches(.app_id) or matches(.window_properties.class))),
         (.. | objects | select(.app_id == "org.omarchy.agent" and matches(.name)))
       ) | .id // empty'
)

[[ -n $id ]] || exit 1

swaymsg "[con_id=$id] focus" >/dev/null
