#!/bin/bash


# anolis:summary=Set and launch the default coding agent
# anolis:args=[qwen|qoder]
# anolis:examples=anolis default agent | anolis default agent qwen | anolis default agent qoder

# Downstream: Anolis desktop adaptation; see UPSTREAM.json and patches.
source /usr/libexec/anolis-agent/env || exit 1

installing=false
if [[ ${1:-} == "--install" ]]; then
  installing=true
  shift
fi

agent_file="$HOME/.config/anolis/defaults/agent"

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

  # Silent when unset rather than defaulting: Anolis 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
qwen | qwencli | qwen-code)
  agent="qwen"; name="Qwen Code"; agent_installer="anolis-install-qwen-cli" ;;
qoder | qodercli)
  agent="qoder"; name="Qoder CLI"; agent_installer="anolis-install-qoder-cli" ;;
*)
  echo "Usage: anolis default agent <qwen|qoder>" >&2
  exit 1 ;;
esac

# Use the upstream installer extension contract for the two providers.
agent_present() { "$agent_installer" --check; }
agent_install() { "$agent_installer" --now; }
if [[ $installing == "false" ]] && ! agent_present; then
  exec anolis-launch-floating-terminal-with-presentation anolis-default-agent --install "$agent"
fi

if ! agent_install; then
  if [[ $installing == "true" && -n ${agent_installer:-} ]]; then
    echo "Could not install $name" >&2
  elif [[ $installing == "true" ]]; then
    echo "Could not install $name with mise" >&2
  else
    echo "Could not set $name as the default coding agent" >&2
  fi
  exit 1
fi

mkdir -p "$(dirname "$agent_file")"
choice_tmp=$(mktemp "${agent_file}.XXXXXX") || exit 1
printf '%s\n' "$agent" >"$choice_tmp"
chmod 600 "$choice_tmp"
mv -f -- "$choice_tmp" "$agent_file"

if [[ $installing == "true" ]]; then
  printf '\033[2J\033[3J\033[H'
  exec anolis-agent --inline
else
  exec anolis-agent
fi
