#!/bin/bash

# omarchy:summary=Launch the default coding agent in a terminal
# omarchy:args=[--inline] [--pick] [--local-model <recipe>] [--agent <id>] [--provider <fireworks|openrouter|deepseek|minimax|synthetic|zai>] [--session <id>|--continue] [--app-id=<app-id>]
# omarchy:examples=omarchy agent | omarchy agent --inline | omarchy agent --agent codex | omarchy agent --provider fireworks

inline=false
pick=false
check_only=false
use_local=false
local_model=""
agent_override=""
provider=""
session=""
continue_last=false
account_home_override=""
account_home_overridden=false
app_id="org.omarchy.agent"
launch_args=("$@")

# Flags only. A bare prompt would shadow the subcommands under this group, so
# prompts go through omarchy-agent-prompt, which passes one here as --prompt.
while (($#)); do
  case "$1" in
    --inline)
      inline=true
      shift
      ;;
    --pick)
      pick=true
      shift
      ;;
    --check)
      check_only=true
      shift
      ;;
    --local-model)
      use_local=true
      local_model=${2:?--local-model needs a recipe id}
      shift 2
      ;;
    --agent)
      agent_override=${2:?--agent needs an agent id}
      shift 2
      ;;
    --provider)
      provider=${2:?--provider needs a provider id}
      shift 2
      ;;
    --session)
      session=${2:?--session needs a value}
      shift 2
      ;;
    --continue)
      continue_last=true
      shift
      ;;
    --account-home=*)
      account_home_override=${1#--account-home=}
      account_home_overridden=true
      shift
      ;;
    # A launcher of its own (Codex, Claude Code, Grok Build) gives its windows
    # their own class, so the dock keeps them under that launcher.
    --app-id=*)
      app_id=${1#--app-id=}
      shift
      ;;
    --prompt)
      prompt=${2:?--prompt needs a value}
      shift 2
      ;;
    *)
      echo "Unexpected argument: $1" >&2
      echo "To pass a prompt: omarchy agent prompt \"$*\"" >&2
      exit 1
      ;;
  esac
done

if [[ -n $session && $continue_last == "true" ]]; then
  echo "Use either --session or --continue, not both." >&2
  exit 2
fi

# Agents refuse to remember trust for $HOME, so launches from the keybinding or
# menu start in the work directory instead of re-asking on every session.
[[ $PWD == "$HOME" && -d $HOME/Work ]] && cd "$HOME/Work"

# --agent launches a given agent instead of the default: the panel's terminal
# button on each subscription opens the harness made for it, Codex for OpenAI.
if [[ -n $agent_override ]]; then
  agent=$agent_override
else
  agent=$(omarchy-default-agent)
fi

# --provider opens a pay-as-you-go provider with no harness of its own
# (Fireworks, OpenRouter, and the agents panel's More list) in OpenCode, where
# the panel's sign-in saves its key.
[[ -n $provider ]] && agent=opencode

# A default of "local" is the local model. It opens in pi, as --local-model
# does whatever the default agent is: the agents panel launches a model
# whether or not a default was chosen. An agent asked for by name is opened
# as asked.
if [[ $agent == "local" ]]; then
  use_local=true
  agent=pi
  # The model the default pins, unless it's since been removed from this
  # machine; a paired machine's is that machine's to answer for.
  pinned=$(cat "$HOME/.config/omarchy/defaults/local-model" 2>/dev/null)
  if [[ -z $local_model && -n $pinned ]]; then
    if [[ $pinned == */* ]] || omarchy-models status --json 2>/dev/null | jq -e --arg recipe "$pinned" '.models[$recipe]' >/dev/null; then
      local_model=$pinned
    fi
  fi
elif [[ $use_local == "true" ]]; then
  agent=pi
fi

# Omarchy ships without a default, so there is nothing to launch until one is
# picked. --pick offers the choice instead of the error, which is what the
# keybinding wants: a keypress that opens nothing explains nothing.
if [[ -z $agent ]]; then
  if [[ $pick == "true" ]]; then
    # The agents panel sets one up, and its agent is started from there, so a
    # prompt (a crash report, a Make something task) waits on the clipboard
    # to paste into it.
    if [[ -n ${prompt:-} ]]; then
      printf '%s' "$prompt" | wl-copy
      omarchy-notification-send -g 󰅇 "$(omarchy-i18n agents.chooseForPrompt)" "$(omarchy-i18n agents.promptOnClipboardBody)"
    fi
    exec omarchy-shell omarchy.agents open
  fi
  echo "Choose default agent with: omarchy default agent <name>" >&2
  exit 1
fi

# OpenClaw's launcher sets OpenClaw up when the package became the seed before
# this user's OpenClaw moved, so with the package a missing command is its to fix.
if [[ $check_only != "true" ]] && omarchy-cmd-missing "$agent" && ! { [[ $agent == "openclaw" ]] && omarchy-pkg-present openclaw; }; then
  # An agent you still have a sign-in for can be missing its CLI: removed, or
  # signed in to on another machine and copied over. Launching it installs the
  # CLI first and then opens as asked, in this terminal or a floating one.
  if omarchy-install-ai-cli --package "$agent" &>/dev/null; then
    if [[ -t 0 ]]; then
      omarchy-install-ai-cli "$agent" || exit 1
    else
      printf -v relaunch '%q ' omarchy-agent "${launch_args[@]}"
      exec omarchy-launch-floating-terminal-with-presentation "omarchy-install-ai-cli $agent && ${relaunch% }"
    fi
  else
    echo "$agent is not installed. Choose an installed agent with: omarchy default agent <name>" >&2
    exit 1
  fi
fi

# Agents launched from the keybinding or menu run unattended, so each one starts
# with its own spelling of "don't stop to ask". Pi and Ori have none to skip.
resume_supported=false
case "$agent" in
opencode)
  resume_supported=true
  command=(opencode --auto)
  if [[ -n $session ]]; then
    command+=(--session "$session")
  elif [[ $continue_last == "true" ]]; then
    command+=(--continue)
  fi
  [[ -n ${prompt:-} ]] && command+=(--prompt "$prompt")
  ;;
agy)
  resume_supported=true
  command=(agy --dangerously-skip-permissions)
  if [[ -n $session ]]; then
    command+=(--conversation "$session")
  elif [[ $continue_last == "true" ]]; then
    command+=(--continue)
  fi
  [[ -n ${prompt:-} ]] && command+=(--prompt-interactive "$prompt")
  ;;
copilot)
  command=(copilot --allow-all)
  [[ -n ${prompt:-} ]] && command+=(--interactive "$prompt")
  ;;
crush)
  # --yolo belongs to the interactive command only; `crush run` never prompts.
  if [[ -n ${prompt:-} ]]; then
    command=(crush run "$prompt")
  else
    command=(crush --yolo)
  fi
  ;;
claude)
  resume_supported=true
  command=(claude --permission-mode auto)
  if [[ -n $session ]]; then
    command+=(--resume "$session")
  elif [[ $continue_last == "true" ]]; then
    command+=(--continue)
  fi
  [[ -n ${prompt:-} ]] && command+=(-- "$prompt")
  ;;
grok)
  command=(grok --permission-mode bypassPermissions)
  [[ -n ${prompt:-} ]] && command+=(-- "$prompt")
  ;;
openclaw)
  # The launcher owns onboarding and the gateway dance: OpenClaw's terminal UI
  # must attach to the running gateway (the embedded `openclaw chat` refuses to
  # start while the gateway owns the state directory). It has no permission
  # prompts to skip, and --message seeds the session while keeping it
  # interactive.
  command=(omarchy-launch-openclaw --tui)
  [[ -n ${prompt:-} ]] && command+=(--message "$prompt")
  ;;
codex)
  resume_supported=true
  if [[ -n $session ]]; then
    command=(codex --approve-for-me resume "$session")
  elif [[ $continue_last == "true" ]]; then
    command=(codex --approve-for-me resume --last)
  else
    command=(codex --approve-for-me)
  fi
  [[ -n ${prompt:-} ]] && command+=(-- "$prompt")
  ;;
cursor-agent)
  # --yolo covers commands only; the workspace trust dialog has its own flag.
  # A one-word prompt naming a subcommand (update, login, help) still runs that
  # subcommand after a bare --, so the agent subcommand is named outright, and
  # -- after it keeps a prompt starting with a dash from being read as an option.
  command=(cursor-agent --yolo --trust)
  [[ -n ${prompt:-} ]] && command+=(agent -- "$prompt")
  ;;
hermes)
  if [[ -n ${prompt:-} ]]; then
    command=(env -u HERMES_SESSION_SOURCE hermes chat --yolo --tui "--query=$prompt")
  else
    command=(hermes --yolo)
  fi
  ;;
muse)
  # --approval-mode never skips the tool prompts but keeps Muse's own sandbox.
  command=(muse --approval-mode never)
  [[ -n ${prompt:-} ]] && command+=(-- "$prompt")
  ;;
omp)
  command=(omp --auto-approve)
  [[ -n ${prompt:-} ]] && command+=(-- "$prompt")
  ;;
ori)
  # Ori is a harness launcher, and `ori code` is the agent it runs itself.
  # A prompt alone means one headless turn there, printed after the turn ends,
  # so --interactive is what seeds the session with it and keeps the window.
  command=(ori code)
  [[ -n ${prompt:-} ]] && command+=(--interactive --prompt "$prompt")
  ;;
pi)
  resume_supported=true
  command=(pi)
  if [[ -n $session ]]; then
    command+=(--session "$session")
  elif [[ $continue_last == "true" ]]; then
    command+=(--continue)
  fi
  [[ -n ${prompt:-} ]] && command+=("$prompt")
  ;;
kimi)
  # --prompt is non-interactive print mode only; it cannot combine with --yolo.
  if [[ -n ${prompt:-} ]]; then
    command=(kimi --prompt "$prompt")
  else
    command=(kimi --yolo)
  fi
  ;;
qwen)
  # Bind the value so a prompt starting with a dash stays literal.
  command=(qwen --yolo)
  [[ -n ${prompt:-} ]] && command+=("--prompt-interactive=$prompt")
  ;;
dsh)
  # The browser UI has no prompt option, and the headless profile would run the
  # prompt with full access in a window that closes with its answer, so a
  # prompt goes to the clipboard below instead.
  command=(env DSH_PERMISSION_MODE=danger-full-access dsh web)
  prompt_via_clipboard="DeepSeek Harness"
  ;;
mcode)
  # The TUI has no no-approval flag; permission options belong to exec mode.
  command=(mcode)
  [[ -n ${prompt:-} ]] && command+=(-- "$prompt")
  ;;
freebuff)
  # Freebuff takes no starting prompt and asks no tool permissions, so a
  # prompt goes to the clipboard below instead.
  command=(freebuff)
  prompt_via_clipboard="Freebuff"
  ;;
kilo)
  # Kilo is built on OpenCode and shares its flags. Bind the prompt so one
  # starting with a dash stays literal.
  resume_supported=true
  command=(kilo --auto)
  if [[ -n $session ]]; then
    command+=(--session "$session")
  elif [[ $continue_last == "true" ]]; then
    command+=(--continue)
  fi
  [[ -n ${prompt:-} ]] && command+=("--prompt=$prompt")
  ;;
devin)
  # A bare positional is a path that opens Devin Desktop, so the prompt
  # always follows --, which starts an interactive session with it.
  command=(devin --permission-mode dangerous --respect-workspace-trust false)
  [[ -n ${prompt:-} ]] && command+=(-- "$prompt")
  ;;
amp)
  # Amp takes its first interactive message from piped input; a positional
  # message is for --execute, which exits after one turn.
  if [[ -n ${prompt:-} ]]; then
    command=(bash -c 'printf "%s\n" "$1" | exec "$0" --dangerously-allow-all' amp "$prompt")
  else
    command=(amp --dangerously-allow-all)
  fi
  ;;
*)
  echo "Unsupported default agent: $agent" >&2
  exit 1
  ;;
esac

if [[ -n $session || $continue_last == "true" ]] && [[ $resume_supported != "true" ]]; then
  echo "$agent does not support --session or --continue; omit it to open a new session with --prompt." >&2
  exit 2
fi

if [[ $check_only == "true" ]]; then
  exit 0
fi

# A model that is set up but not running, as one opened from its launcher may
# be, is started first, in the terminal the agent will have: loading takes a
# minute or so, and omarchy-models-warmup puts on a show for it there. So
# a launch from outside a terminal reruns itself inside one. A model on a
# paired machine is that machine's to start.
if [[ $use_local == "true" && $local_model != */* ]]; then
  local_state=$(omarchy-models status --json 2>/dev/null | jq -r --arg recipe "$local_model" '
    (if $recipe == "" then .last // "" else $recipe end) as $recipe
    | .models[$recipe] // empty | "\(.unit)/\(.sub_state)"' 2>/dev/null)
  if [[ -n $local_state && $local_state != "active/running" ]]; then
    if [[ $inline == "true" ]]; then
      omarchy-models-warmup ${local_model:+"$local_model"} || exit 1
    else
      exec omarchy-launch-tui --app-id="$app_id" omarchy-agent --inline "${launch_args[@]}"
    fi
  fi
fi

# A local model points pi at the model `omarchy models use` runs, through a
# launch-time overlay Omarchy owns, never by editing pi's own config.
if [[ $use_local == "true" ]]; then
  mapfile -t overlay < <(omarchy-models overlay pi ${local_model:+"$local_model"})
  if (( ${#overlay[@]} != 3 )); then
    omarchy-notification-send -u critical "$(omarchy-i18n agents.localMissing)" "$(omarchy-i18n agents.localMissingBody)"
    exit 1
  fi
  command+=(--extension "${overlay[0]}" --provider "${overlay[1]}" --model "${overlay[2]}")
fi

# --provider starts the session on one of the provider's models, passed at
# launch rather than written to the agent's config, so it never opens on
# another provider: the model the agent last used there, so a switch made in
# a session sticks; else the one the provider's usage record has spent most
# tokens on; else the first the agent lists. The record names a model by its
# short name ("deepseek-v4.1-flash"), so the agent's own list supplies the id
# it knows it by ("accounts/fireworks/models/deepseek-v4p1-flash"). An agent
# that lists no models for the provider opens as it was.
if [[ -n $provider ]]; then
  provider_id=$provider
  [[ $provider == "fireworks" ]] && provider_id="fireworks-ai"
  provider_models=$(opencode models 2>/dev/null | sed -n "s|^$provider_id/||p")
  # OpenCode keeps the models it used, latest first.
  provider_last=$(jq -r --arg provider "$provider_id" 'first(.recent[]? | select(.providerID == $provider) | .modelID) // empty' \
    "${XDG_STATE_HOME:-$HOME/.local/state}/opencode/model.json" 2>/dev/null)

  provider_record="${XDG_STATE_HOME:-$HOME/.local/state}/omarchy/agents/usage/$provider.json"
  provider_model=$(awk -v last="$provider_last" '
    FILENAME == ARGV[1] { used[++count] = $0; next }
    $0 == "" { next }
    {
      if (first == "") first = $0
      listed[$0] = 1
      short = $0
      sub(/.*\//, "", short)
      while (match(short, /[0-9]p[0-9]/)) short = substr(short, 1, RSTART) "." substr(short, RSTART + 2)
      if (!(short in id)) id[short] = $0
    }
    END {
      if (last in listed) { print last; exit }
      for (i = 1; i <= count; i++) if (used[i] in id) { print id[used[i]]; exit }
      print first
    }
  ' <(jq -r '.modelUsage // {} | to_entries | sort_by(-([.value[]? | numbers] | add // 0)) | .[].key' "$provider_record" 2>/dev/null) \
    <(printf '%s\n' "$provider_models"))

  if [[ -n $provider_model ]]; then
    # The shared background service never sees the choice, so run a private one.
    model=$(jq -nc --arg model "$provider_id/$provider_model" '{model: $model}')
    command=(env "OPENCODE_CONFIG_CONTENT=$model" "${command[@]}" --standalone)
  fi
fi

# An agent with no way to take a starting prompt still opens, with the prompt
# on the clipboard to paste as its first message, so a prompted launch from the
# agents panel or a crash report is not lost.
if [[ -n ${prompt:-} && -n ${prompt_via_clipboard:-} ]]; then
  printf '%s' "$prompt" | wl-copy
  omarchy-notification-send -g 󰅇 "$(omarchy-i18n agents.promptOnClipboard "$prompt_via_clipboard")" \
    "$(omarchy-i18n agents.promptOnClipboardBody)"
fi

# A new session uses the current selection rather than its parent's account
# pin. Explicit provider homes still override the selection. Carry the new pin
# in the command, since terminals launched through uwsm don't inherit our env.
case "$agent" in
claude) home_env="CLAUDE_CONFIG_DIR" ;;
codex) home_env="CODEX_HOME" ;;
grok) home_env="GROK_HOME" ;;
*) home_env="" ;;
esac
if [[ -n $home_env ]]; then
  account_pin="OMARCHY_AGENT_${agent^^}_HOME"
  if [[ $account_home_overridden == "true" ]]; then
    account_env=(env -u "$home_env" "$account_pin=$account_home_override")
    [[ -n $account_home_override ]] && account_env+=("$home_env=$account_home_override")
    command=("${account_env[@]}" "${command[@]}")
  else
    if [[ -v $account_pin && ${!home_env:-} == "${!account_pin}" ]]; then
      unset "$home_env"
    fi
    unset "$account_pin"
    if [[ -z ${!home_env:-} ]]; then
      home=$(omarchy-agent-account-home "$agent")
      account_env=(env -u "$home_env" "$account_pin=$home")
      [[ -n $home ]] && account_env+=("$home_env=$home")
      command=("${account_env[@]}" "${command[@]}")
    elif [[ $inline != "true" ]]; then
      command=(env "$home_env=${!home_env}" "${command[@]}")
    fi
  fi
fi

# Agents that never set a window title of their own get a proper name instead
# of their binary's ("agy").
case "$agent" in
agy) title="◆ Antigravity" ;;
*) title="" ;;
esac

if [[ $inline == "true" ]]; then
  [[ -n $title ]] && printf '\e]2;%s\a' "$title"
  exec "${command[@]}"
else
  # A fixed app-id rather than the default org.omarchy.<binary>, so every agent
  # window shares one class for window rules and themes to single out.
  exec omarchy-launch-tui --app-id="$app_id" ${title:+"--title=$title"} "${command[@]}"
fi
