#!/bin/bash

# omarchy:summary=Set and launch the default coding agent
# omarchy:args=[local|pi|omp|opencode|ori|claude|codex|grok|openclaw|agy|hermes|copilot|crush|cursor-agent|muse|kimi|qwen|dsh|mcode|freebuff|kilo|devin|amp]
# omarchy:examples=omarchy default agent | omarchy default agent codex | omarchy default agent local | omarchy default agent local qwen3.8-27b-gufo

installing=false
checking=false
selecting=false
if [[ ${1:-} == "--install" ]]; then
  installing=true
  shift
elif [[ ${1:-} == "--installed" ]]; then
  # --installed <agent> only answers whether that harness is installed, with
  # its exit status, and selects nothing.
  checking=true
  shift
  (($# == 1)) || exit 1
elif [[ ${1:-} == "--select" ]]; then
  # --select <agent> makes an installed agent the default without opening it,
  # for the agents panel's star.
  selecting=true
  shift
  # A local model to pin may follow "local".
  (($# == 1)) || { [[ $1 == "local" ]] && (($# == 2)); } || exit 1
fi

agent_file="$HOME/.config/omarchy/defaults/agent"
# The local model a default of "local" opens: a recipe, or host/recipe for one
# a paired machine shares. Without one it opens the model started last.
local_model_file="$HOME/.config/omarchy/defaults/local-model"

if (($# == 0)); then
  if [[ -f $agent_file ]]; then
    read -r agent <"$agent_file"
  fi

  # Silent when unset rather than defaulting: Omarchy picks no agent for you, so
  # the menu leaves every entry unchecked until one is chosen.
  [[ -n ${agent:-} ]] && echo "$agent"
  exit 0
fi

case "$1" in
local) agent="local"; name="Local model" ;;
pi) agent="pi"; name="Pi" ;;
omp | oh-my-pi) agent="omp"; name="Oh My Pi" ;;
opencode | open-code) agent="opencode"; name="OpenCode" ;;
ori | openrouter) agent="ori"; name="Ori" ;;
claude | claude-code) agent="claude"; name="Claude Code" ;;
codex) agent="codex"; name="Codex" ;;
crush) agent="crush"; name="Crush" ;;
grok) agent="grok"; name="Grok" ;;
openclaw) agent="openclaw"; name="OpenClaw"; agent_installer="omarchy-install-openclaw-cli" ;;
agy | antigravity | antigravity-cli | gemini | gemini-cli) agent="agy"; name="Antigravity" ;;
hermes) agent="hermes"; name="Hermes"; agent_installer="omarchy-install-hermes-cli" ;;
copilot | github-copilot) agent="copilot"; name="GitHub Copilot" ;;
muse | muse-code | musecode) agent="muse"; name="Muse Code" ;;
cursor | cursor-agent) agent="cursor-agent"; name="Cursor CLI" ;;
kimi | kimi-code) agent="kimi"; name="Kimi" ;;
qwen | qwen-code) agent="qwen"; name="Qwen Code" ;;
dsh | deepseek | deepseek-harness) agent="dsh"; name="DeepSeek Harness" ;;
mcode | minimax-code | minimax) agent="mcode"; name="MiniMax Code" ;;
freebuff) agent="freebuff"; name="Freebuff" ;;
kilo | kilocode | kilo-code) agent="kilo"; name="Kilo" ;;
devin | devin-cli) agent="devin"; name="Devin CLI" ;;
amp | ampcode) agent="amp"; name="Amp" ;;
*)
  echo "Usage: omarchy-default-agent <local|pi|omp|opencode|ori|claude|codex|grok|openclaw|agy|hermes|copilot|crush|cursor-agent|muse|kimi|qwen|dsh|mcode|freebuff|kilo|devin|amp>"
  exit 1
  ;;
esac

# Hermes and OpenClaw are self-updating runtimes in the user's home, Hermes the
# desktop app's and OpenClaw the one its Control UI updates; see
# omarchy-install-hermes-cli and omarchy-install-openclaw-cli. Every other agent
# is a package that omarchy-install-ai-cli installs.
if [[ -n ${agent_installer:-} ]]; then
  # Not omarchy-cmd-present: a command on PATH says nothing about whether the
  # install behind it finished or runs the sessions omarchy-agent starts.
  # Treating it as installed would skip the floating terminal and run a
  # minutes-long install inside the menu action instead.
  agent_present() { "$agent_installer" --check; }
  agent_install() { "$agent_installer" --now; }
elif [[ $agent == "pi" || $agent == "local" ]]; then
  # Pi is one of Omarchy's base packages, and the local model opens in it, so
  # there is nothing to install.
  agent_present() { true; }
  agent_install() { true; }
else
  agent_present() { omarchy-install-ai-cli --check "$agent"; }
  agent_install() { omarchy-install-ai-cli "$agent"; }
fi

if [[ $checking == "true" ]]; then
  agent_present
  exit
fi

if [[ $selecting == "true" ]] && ! agent_present; then
  # The agents panel's star on a subscription whose CLI isn't installed here
  # installs it in a terminal, then makes it the default.
  if [[ -z ${agent_installer:-} && $agent != "local" && $agent != "pi" ]]; then
    exec omarchy-launch-floating-terminal-with-presentation "omarchy-install-ai-cli $agent && omarchy-default-agent --select $agent"
  fi
  echo "$name is not installed" >&2
  exit 1
elif [[ $installing == "false" ]] && ! agent_present; then
  exec omarchy-launch-floating-terminal-with-presentation omarchy-default-agent --install "$agent"
fi

if [[ $installing == "true" ]] && ! agent_install; then
  echo "Could not install $name" >&2
  exit 1
fi

mkdir -p "$(dirname "$agent_file")"
printf '%s\n' "$agent" >"$agent_file"
if [[ $agent == "local" && -n ${2:-} ]]; then
  printf '%s\n' "$2" >"$local_model_file"
elif [[ $agent == "local" ]]; then
  rm -f "$local_model_file"
fi

# An installed harness gets a launcher of its own beside Agent, as signing in
# to a subscription adds one, and claude, codex or grok its account dispatcher.
omarchy-agent-launcher "$agent" || true
omarchy-agent-account-dispatch "$agent"

# The harness reads the shared ~/.agents/AGENTS.md from its first session.
omarchy-agent-instructions "$agent" >/dev/null || true

[[ $selecting == "true" ]] && exit 0

if [[ $installing == "true" ]]; then
  # The installer's own window: the nearest ancestor Hyprland knows as a client.
  installer=""
  clients=$(hyprctl clients -j 2>/dev/null)
  pid=$PPID
  while [[ -n $clients && -z $installer ]] && (( pid > 1 )); do
    installer=$(jq -r --argjson pid "$pid" '.[]? | select(.pid == $pid) | "\(.address) \(.workspace.name)"' <<<"$clients" 2>/dev/null)
    pid=$(ps -o ppid= -p "$pid" 2>/dev/null)
  done

  # A terminal that serves every window from one process (foot's server, a
  # single-instance Ghostty or Kitty) matches them all. A title only this
  # window carries picks it out. Terminals apply a title on their next frame,
  # so give it a moment; if it never shows, the installer stays unknown and the
  # agent opens here as it would outside the console.
  if [[ $installer == *$'\n'* ]]; then
    title="omarchy-default-agent-$$"
    printf '\033]2;%s\007' "$title"
    installer=""
    for _ in {1..20}; do
      installer=$(hyprctl clients -j 2>/dev/null | jq -r --arg title "$title" '[.[]? | select(.title == $title)][0] // empty | "\(.address) \(.workspace.name)"' 2>/dev/null)
      [[ -n $installer ]] && break
      sleep 0.05
    done
    printf '\033]2;Armbian\007'
  fi
fi

# An install started from the Quake console floats only while it installs. The
# agent then takes its place in the console as the tiled window the console is
# shaped around, rather than running inline in a floating terminal over it.
if [[ $installing == "true" && ${installer#* } == "special:qconsole" ]]; then
  hyprctl dispatch 'hl.dsp.exec_cmd("omarchy-agent", { workspace = "special:qconsole silent" })' >/dev/null
  hyprctl dispatch "hl.dsp.window.close({ window = \"address:${installer%% *}\" })" >/dev/null
elif [[ $installing == "true" ]]; then
  printf '\033[2J\033[3J\033[H'
  exec omarchy-agent --inline
else
  exec omarchy-agent
fi
