#!/bin/bash

# omarchy:summary=Sign in to an agent subscription
# omarchy:args=[--check] [--events] [--reauth <account>] [agy|claude|codex|copilot|cursor|deepseek|fireworks|grok|minimax|muse|opencode|openrouter|synthetic|zai] [label]
# omarchy:examples=omarchy agent account add claude | omarchy agent account add Work | omarchy agent account add codex Side | omarchy agent account add muse

set -uo pipefail

# --check prints, per provider, whether adding one now would be its first
# sign-in, an additional account, or not possible yet. --events is for the
# agents panel: progress arrives as `@@omarchy <event> <detail>` lines mixed
# into the CLI's own output (which carries codes the panel shows), nothing
# waits on a terminal, and the result also lands as a notification in case
# the panel has closed.
# --reauth <account> signs an account that's already here in again, in its
# own home, for when its sign-in has lapsed.
check=false
events=false
reauth=""
usage() {
  echo "Usage: omarchy-agent-account-add [--check] [--events] [--reauth <account>] [agy|claude|codex|copilot|cursor|deepseek|fireworks|grok|minimax|muse|opencode|openrouter|synthetic|zai] [label]" >&2
  exit 1
}

while [[ ${1:-} == --* ]]; do
  case "$1" in
  --check) check=true ;;
  --events) events=true ;;
  --reauth)
    reauth="${2:-}"
    [[ -n $reauth && $reauth != --* ]] || usage
    shift
    ;;
  *) break ;;
  esac
  shift
done

# Whether a provider's own home (~/.claude, ~/.codex, ~/.grok) is signed in.
# For Claude that's whichever account sessions use, not always the primary.
primary_signed_in() {
  omarchy-agent-account-state list "$1" | jq -e --arg home "$HOME/.$1" '.[0].accounts | any(.home == $home and .signedIn)' >/dev/null
}

if [[ $check == "true" ]]; then
  for p in claude codex grok; do
    if primary_signed_in "$p"; then
      echo "$p additional"
    else
      echo "$p first"
    fi
  done
  # The rest keep one sign-in each, which signing in again replaces.
  printf '%s first\n' agy copilot cursor deepseek fireworks minimax muse opencode openrouter synthetic zai
  exit 0
fi

# The provider can be left out when it's your default agent:
# `omarchy agent account add Work`.
if [[ ! ${1:-} =~ ^(agy|gemini|claude|codex|copilot|cursor|cursor-agent|deepseek|fireworks|grok|minimax|muse|opencode|openrouter|synthetic|zai)$ ]]; then
  default=$(omarchy-default-agent)
  [[ $default == "claude" || $default == "codex" || $default == "grok" ]] && set -- "$default" "$@"
fi

# Claude, Codex, and Grok can hold several accounts, each in a home of its
# own. The rest keep the one sign-in their CLI does. `harness` is the command
# that codes on the subscription, when it isn't the provider's own name.
accounts=false
key_provider=""
case "${1:-}" in
claude) provider="claude"; name="Claude"; app="Claude Code"; site="claude.ai"; home_env="CLAUDE_CONFIG_DIR"; accounts=true ;;
codex) provider="codex"; name="Codex"; app="Codex"; site="chatgpt.com"; home_env="CODEX_HOME"; accounts=true ;;
grok) provider="grok"; name="Grok"; app="Grok Build"; site="x.ai"; home_env="GROK_HOME"; accounts=true ;;
# A Gemini subscription is signed in to through Antigravity, its harness.
agy | gemini) provider="agy"; name="Gemini"; app="Antigravity"; login_command=(agy acp --login) ;;
muse) provider="muse"; name="Muse"; app="Muse Code"; login_command=(muse login) ;;
# One OpenCode Console sign-in covers Zen and Go.
opencode) provider="opencode"; name="OpenCode"; app="OpenCode"; login_command=(opencode auth login opencode --method device) ;;
copilot) provider="copilot"; name="Copilot"; app="GitHub Copilot"; login_command=(copilot login) ;;
cursor | cursor-agent) provider="cursor"; harness="cursor-agent"; name="Cursor"; app="Cursor CLI"; login_command=(cursor-agent login) ;;
# Pay as you go, with OpenCode's id for each: Fireworks and OpenRouter, and
# the panel's More list, providers whose usage Omarchy reads, so their keys
# can be checked before they're saved.
fireworks) provider="fireworks"; name="Fireworks"; key_provider="fireworks-ai" ;;
openrouter) provider="openrouter"; name="OpenRouter"; key_provider="openrouter" ;;
deepseek) provider="deepseek"; name="DeepSeek"; key_provider="deepseek" ;;
minimax) provider="minimax"; name="MiniMax"; key_provider="minimax" ;;
synthetic) provider="synthetic"; name="Synthetic"; key_provider="synthetic" ;;
zai) provider="zai"; name="Z.ai"; key_provider="zai" ;;
*) usage ;;
esac
# What's ready once signed in: the agent's own app, or for a key, the
# provider, which OpenCode only runs.
ready_name=${app-}
# No CLI of their own: an API key is the sign-in, and OpenCode runs on it.
if [[ -n $key_provider ]]; then
  harness="opencode"; app="OpenCode"; login_command=(key_login "$key_provider")
  ready_name=$name
fi
harness=${harness-$provider}
label="${2:-}"

say() {
  if [[ $events == "true" ]]; then
    printf '@@omarchy status %s\n' "$*"
  else
    echo "$*"
  fi
}

# A signed-in agent gets a launcher of its own beside Agent, drawn by the
# icon set: Claude Code, Codex, or Grok Build, whatever the default agent is.
install_launcher() {
  omarchy-agent-launcher "$harness"
}

# The first agent signed in on a machine with none chosen becomes the
# default, so `omarchy agent` and the panel's starter prompts have one to run.
# A default someone already picked is never touched.
default_if_unset() {
  if [[ -z $(omarchy-default-agent) ]]; then
    mkdir -p "$HOME/.config/omarchy/defaults"
    printf '%s\n' "$1" >"$HOME/.config/omarchy/defaults/agent"
  fi
}

# A first sign-in announces the agent as ready, an added account that it's
# ready for more, and signing in again that it's ready again; clicking one
# starts the agent. An added account that sessions couldn't switch to says so.
# Each stays up until it's clicked or closed: the sign-in finishes in the
# browser, where a toast that leaves on its own goes unseen.
finish() {
  # An agent hidden from the panel, as removing its sign-in does, shows again
  # however it was signed in to.
  omarchy-shell omarchy.agents showAgent "$provider" true >/dev/null 2>&1
  install_launcher
  # A Claude subscription brings the Claude browser extension with it. The
  # installer is passwordless through etc/sudoers.d/omarchy-chromium-claude
  # and does nothing once the extension is seeded.
  if [[ $provider == "claude" ]]; then
    interruptible omarchy-install-chromium-claude </dev/null >/dev/null 2>&1 || true
  fi
  if [[ $events == "true" ]]; then
    printf '@@omarchy done %s\n' "$1"
    if [[ ${2:-} == "ready" ]]; then
      omarchy-notification-send --sticky -g 󰚩 --image "$(omarchy-agent-logo "$provider")" \
        "$(omarchy-i18n agents.readyToCode "$ready_name")" "$(omarchy-i18n agents.readyToCodeBody)" \
        --exec omarchy-agent --agent "$harness" --app-id="org.omarchy.$harness"
    elif [[ ${2:-} == "more" ]]; then
      omarchy-notification-send --sticky -g 󰚩 --image "$(omarchy-agent-logo "$provider")" \
        "$(omarchy-i18n agents.readyForMore "$ready_name")" "$(omarchy-i18n agents.readyForMoreBody "$3")" \
        --exec omarchy-agent --agent "$harness" --app-id="org.omarchy.$harness"
    elif [[ ${2:-} == "again" ]]; then
      # A click starts the agent only when sessions use the renewed account;
      # otherwise it would start on another one.
      start=()
      if [[ $3 == "1" ]]; then
        start=(--exec omarchy-agent --agent "$harness" --app-id="org.omarchy.$harness")
      fi
      omarchy-notification-send --sticky -g 󰚩 --image "$(omarchy-agent-logo "$provider")" \
        "$(omarchy-i18n agents.readyAgain "$ready_name")" "$(omarchy-i18n agents.readyAgainBody)" "${start[@]}"
    else
      omarchy-notification-send --sticky -g 󰚩 --image "$(omarchy-agent-logo "$provider")" \
        "$(omarchy-i18n agents.addedNotSelectedTitle "$3")" "$(omarchy-i18n agents.addedNotSelectedBody)"
    fi
  else
    echo
    echo "$1"
  fi
}

# Accounts just added, fresh or recovered, are the ones you want tokens from
# next, so sessions switch to the newest: running Claude sessions too, and new
# ones for the others. If the choice can't be saved, the accounts are still
# added and say so.
announce_added() {
  local added newest used
  added=$(jq -r 'map(.label + (if .email != "" then " (" + .email + ")" else "" end)) | join(", ")' <<<"$1")
  newest=$(jq -c 'last' <<<"$1")
  if used=$(omarchy-agent-account-state use "$provider" "$(jq -r .id <<<"$newest")"); then
    omarchy-agent-usage-update --force "$provider" >/dev/null 2>&1 &
    finish "$(omarchy-i18n agents.added "$added")" more "$(jq -r .label <<<"$newest")"
    if [[ $events != "true" ]]; then
      if [[ $(jq -r .seated <<<"$used") == "true" ]]; then
        echo "$name sessions now use $(jq -r .label <<<"$newest"), running ones included."
      else
        echo "New $name sessions now use $(jq -r .label <<<"$newest")."
      fi
    fi
  else
    omarchy-agent-usage-update --force "$provider" >/dev/null 2>&1 &
    finish "$(omarchy-i18n agents.addedNotSelected "$added")" unswitched "$(jq -r .label <<<"$newest")"
  fi
}

fail() {
  if [[ $events == "true" ]]; then
    printf '@@omarchy error %s\n' "$1"
    omarchy-notification-send -g 󰚩 --image "$(omarchy-agent-logo "$provider")" -u critical "$(omarchy-i18n agents.addFailed "$name")" "$1"
  else
    echo "$1" >&2
  fi
  exit 1
}

# Cancelling from the panel stops the CLI's login too, and leaves no
# half-made home behind.
home=""
browser=""
cleanup() {
  [[ -n $browser ]] && rm -f "$browser"
  [[ -n $home && -d $home && $home == */.pending/* ]] && rm -rf "$home"
}
trap cleanup EXIT
trap 'pkill -TERM -P $$; exit 130' TERM INT

# Bash holds a trap until a foreground command finishes, and a login waits on
# the browser for as long as it takes. Running it in the background behind a
# `wait` lets Cancel stop it at once. It keeps this script's stdin, where the
# panel sends a pasted code.
interruptible() {
  "$@" <&0 &
  wait $!
}

# Each agent's CLI is a package installed the first time it's needed. Signing
# in is often that time, so the install happens here, where the panel can show
# it, rather than looking like the login hanging. pacman only draws progress
# bars on a terminal, so the installer runs with a PTY on stdout while stdin
# stays on /dev/null (keeping polkit graphical and non-terminal). The runner
# sits behind a `wait`, like a login, so Cancel ends the add at once without
# waiting on a privileged pacman transaction.
install_cli() {
  if [[ $events != "true" ]]; then
    "$@"
    return
  fi

  printf '@@omarchy progress 0 0 0\n'
  python3 - "$@" <<'PY' &
import errno, fcntl, os, pty, re, signal, struct, subprocess, sys, termios

UNITS = {"B": 1, "KB": 1000, "KIB": 1024, "MB": 1000**2, "MIB": 1024**2, "GB": 1000**3, "GIB": 1024**3}
SPLIT = re.compile(r"\r+|\n+|\x1b\[\d*[EFGH]")
ANSI = re.compile(r"\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)")
BAR_END = re.compile(r"\[[^\]]*\]\s+\d+%$")
DL_RE = re.compile(r"(\d+(?:[.,]\d+)?)\s*([KMG]?i?B)/s\s+(?:\d+(?::\d+)+|--:--)\s+\[[^\]]*\]\s+(\d+)%")
TOTAL_RE = re.compile(r"^\s*\S+\s+\(\d+/\d+\)\s+")
INST_RE = re.compile(r"^\s*\((\d+)/(\d+)\)\s+.*\[[^\]]*\]\s+(\d+)%")
BAR_RE = re.compile(r"\[[^\]]*\]\s+(\d+)%")

master_fd, slave_fd = pty.openpty()
fcntl.ioctl(slave_fd, termios.TIOCSWINSZ, struct.pack("HHHH", 24, 120, 0, 0))
attrs = termios.tcgetattr(slave_fd)
attrs[3] &= ~termios.ECHO
termios.tcsetattr(slave_fd, termios.TCSANOW, attrs)

proc = subprocess.Popen(sys.argv[1:], stdin=subprocess.DEVNULL, stdout=slave_fd, stderr=slave_fd)
os.close(slave_fd)

def stop(_sig, _frame):
  for fn in (proc.terminate, lambda: os.close(master_fd)):
    try: fn()
    except OSError: pass
  os._exit(130)

signal.signal(signal.SIGTERM, stop)
signal.signal(signal.SIGINT, stop)

last = None
seen_total = False
stage = 0
verify_step = 0

def emit(pct, rate, name):
  global last
  state = (pct, rate, name)
  if state != last:
    sys.stdout.write(f"@@omarchy progress {pct} 100 {rate} {name}\n")
    sys.stdout.flush()
    last = state

def handle(raw):
  global seen_total, stage, verify_step
  line = ANSI.sub("", raw).strip()
  if not line:
    return
  if m := DL_RE.search(line):
    if stage > 1 or ".sig" in line:
      return
    if TOTAL_RE.match(line):
      seen_total = True
    elif seen_total:
      return
    stage = 1
    rate = int(float(m.group(1).replace(",", ".")) * UNITS.get(m.group(2).upper(), 1))
    emit(min(100, int(m.group(3))), rate, "downloading")
  elif m := INST_RE.match(line):
    stage = 3
    i, n, p = int(m.group(1)), max(1, int(m.group(2))), int(m.group(3))
    emit(min(95, int(((i - 1) * 100 + p) * 95 / (n * 100))), 0, "installing")
  elif stage <= 2 and (m := BAR_RE.search(line)):
    stage = 2
    p = int(m.group(1))
    emit(min(100, verify_step * 25 + p // 4), 0, "verifying")
    if p >= 100:
      verify_step = min(3, verify_step + 1)
  elif stage >= 3 and line.startswith("::"):
    emit(98, 0, "installing")

buf = ""
while True:
  try:
    chunk = os.read(master_fd, 4096)
  except OSError as exc:
    if exc.errno == errno.EIO:
      break
    raise
  if not chunk:
    break
  buf += chunk.decode("utf-8", errors="replace")
  parts = SPLIT.split(buf)
  for part in parts[:-1]:
    handle(part)
  buf = parts[-1]
  if BAR_END.search(ANSI.sub("", buf).rstrip()):
    handle(buf)
    buf = ""

if buf:
  handle(buf)
os.close(master_fd)
sys.exit(proc.wait())
PY
  wait $!
}

if ! omarchy-install-ai-cli --check "$harness"; then
  say "$(omarchy-i18n agents.installingCli "$name")"
  install_cli omarchy-install-ai-cli "$harness" || fail "$(omarchy-i18n agents.installCliFailed "$name")"
fi
# A CLI installed outside Omarchy has no account dispatcher yet.
omarchy-agent-account-dispatch "$harness"

# Your main browser is almost certainly signed in to the account you already
# have, and a login would quietly reuse it. The CLIs open their login page
# through $BROWSER, so this points it at a private window instead.
private_browser() {
  browser=$(mktemp "${XDG_RUNTIME_DIR:-/tmp}/omarchy-account-browser.XXXXXX") || fail "$(omarchy-i18n agents.homeFailed)"
  printf '#!/bin/bash\nexec omarchy-launch-browser --private "$1"\n' >"$browser" || fail "$(omarchy-i18n agents.homeFailed)"
  chmod +x "$browser" || fail "$(omarchy-i18n agents.homeFailed)"
}

# Pay-as-you-go providers have no login to run: an API key is the sign-in.
# It's saved in OpenCode, which runs on it, and travels only through the
# environment and stdin, never a command line. A key the provider refuses is
# not saved, and says so by returning 2.
key_login() {
  local opencode_provider=$1
  local key id
  if [[ $events == "true" ]]; then
    read -r key
  else
    key=$(gum input --password --prompt "$name API key: ")
  fi
  [[ -n $key ]] || return 1
  # The provider has to answer for the key: a refusal returns 2, and a check
  # that couldn't reach it returns 3, so it can be tried again rather than
  # saving a key nobody has vouched for.
  local status check_home check_args=(--force)
  # Fireworks answers for a key in a second, but its full usage takes about
  # twenty, so it only checks the key.
  [[ $provider == "fireworks" ]] && check_args=(--check-key)
  check_home=$(mktemp -d) || return 3
  status=$(env HOME="$check_home" XDG_CONFIG_HOME="$check_home/.config" XDG_DATA_HOME="$check_home/.local/share" \
    XDG_STATE_HOME="$check_home/.local/state" XDG_CACHE_HOME="$check_home/.cache" "${provider^^}_API_KEY=$key" \
    "omarchy-agent-usage-$provider" "${check_args[@]}" | jq -r '.usageStatusText // "unreadable"')
  local check_status=$?
  rm -rf "$check_home"
  (( check_status == 0 )) || return 3
  # A key the provider answered for is fine even when the account is empty,
  # and OpenRouter says its balance is unavailable only after the key itself
  # was accepted; any other status means the provider wasn't reached.
  case $status in
  "" | "Out of credits") ;;
  "Sign-in expired") return 2 ;;
  "Balance unavailable") [[ $provider == "openrouter" ]] || return 3 ;;
  *) return 3 ;;
  esac

  # OpenCode imports a credential as inactive when it already has one.
  id="omarchy-$EPOCHSECONDS"
  KEY=$key jq -n --arg id "$id" --arg provider "$opencode_provider" --arg label "$name" \
    '[{id: $id, integrationID: $provider, label: $label, active: true, value: {type: "key", key: env.KEY}}]' |
    opencode auth import >/dev/null 2>&1 && opencode auth switch "$opencode_provider" "$id" >/dev/null 2>&1
}

# One sign-in, where the CLI always keeps it, through your normal browser:
# adding it and signing in again are the same login. The CLI's whole output
# goes to the panel, which shows the code it prints to confirm in the browser.
if [[ $accounts == "false" ]]; then
  # Gemini's page ends on a code to paste back, and a key is all there is to
  # a key's sign-in; the panel shows a field for either, under what it's for.
  if [[ $events == "true" && $provider == "agy" ]]; then
    printf '@@omarchy paste %s\n' "$(omarchy-i18n agents.pasteSignInCode)"
  fi
  if [[ -z $key_provider ]]; then
    say "$(omarchy-i18n agents.signInBrowser "$name")"
  elif [[ $events == "true" ]]; then
    printf '@@omarchy key %s\n@@omarchy status %s\n' "$(omarchy-i18n agents.apiKeyHint "$name")" "$(omarchy-i18n agents.apiKeyHint "$name")"
  fi
  interruptible "${login_command[@]}" 2>&1
  login_status=$?
  if (( login_status == 2 )) && [[ -n $key_provider ]]; then
    fail "$(omarchy-i18n agents.keyRefused "$name")"
  elif (( login_status == 3 )) && [[ -n $key_provider ]]; then
    fail "$(omarchy-i18n agents.keyUnchecked "$name")"
  elif (( login_status != 0 )); then
    fail "$(omarchy-i18n agents.signInFailed "$name")"
  fi

  omarchy-agent-usage-update --force "$provider" >/dev/null 2>&1 &
  default_if_unset "$harness"
  finish "$(omarchy-i18n agents.signedIn "$name")" ready
  exit 0
fi

case "$provider" in
claude) login_command=(claude auth login) ;;
codex) login_command=(codex login) ;;
grok) login_command=(grok login) ;;
esac

# The CLI's own home, whatever this shell has pointed it at.
login() {
  interruptible env -u CLAUDE_CONFIG_DIR -u CODEX_HOME -u GROK_HOME "OMARCHY_AGENT_${provider^^}_HOME=" "${login_command[@]}" 2>&1
}

# Signing an account that's already here in again: the primary through the
# normal browser, an added one through a private window. Its home is never
# recreated or removed.
if [[ -n $reauth ]]; then
  found=$(omarchy-agent-account-state homes "$provider" | awk -F'\t' -v id="$reauth" '$1 == id || (id == ":primary" && $4 == "1")' | head -1)
  account_home=$(cut -f2 <<<"$found")
  [[ -n $account_home ]] || fail "$(omarchy-i18n agents.noAccountNamed "$name" "$reauth")"

  # A Claude login can move while the browser is open, so it signs in to a
  # scratch home and is installed wherever the account's login is by then.
  if [[ $provider == "claude" ]]; then
    home=$(omarchy-agent-account-state begin "$provider" "" "$$") || fail "$(omarchy-i18n agents.homeFailed)"
    target="$home"
  else
    target="$account_home"
  fi
  where=(env -u CLAUDE_CONFIG_DIR -u CODEX_HOME -u GROK_HOME "OMARCHY_AGENT_${provider^^}_HOME=")
  [[ $target != "$HOME/.$provider" ]] && where+=("$home_env=$target")

  if [[ $(cut -f4 <<<"$found") == "1" ]]; then
    say "$(omarchy-i18n agents.signInAgainBrowser "$name")"
    interruptible "${where[@]}" "${login_command[@]}" 2>&1 || fail "$(omarchy-i18n agents.signInFailed "$name")"
  else
    say "$(omarchy-i18n agents.signInAgainPrivate)"
    private_browser
    interruptible "${where[@]}" BROWSER="$browser" "${login_command[@]}" 2>&1 || fail "$(omarchy-i18n agents.signInFailed "$name")"
  fi
  if [[ $provider == "claude" ]]; then
    installed=$(omarchy-agent-account-state relogin "$provider" "$(cut -f1 <<<"$found")" "$home" 2>&1) || fail "$installed"
  fi

  omarchy-agent-usage-update --force "$provider" >/dev/null 2>&1 &
  finish "$(omarchy-i18n agents.signedInAgain "$name")" again "$(cut -f3 <<<"$found")"
  exit 0
fi

# The first subscription signs in where the CLI always looks, through your
# normal browser: nothing is signed in there yet that it could be mistaken for.
if ! primary_signed_in "$provider"; then
  say "$(omarchy-i18n agents.signInBrowser "$name")"
  if login && primary_signed_in "$provider"; then
    default_if_unset "$provider"
    omarchy-agent-usage-update --force "$provider" >/dev/null 2>&1 &
    finish "$(omarchy-i18n agents.signedIn "$name")" ready
  else
    fail "$(omarchy-i18n agents.signInFailed "$name")"
  fi
else
  # Retry the final registration of a completed, interrupted sign-in before
  # asking for another browser login. Live sign-ins are never recovered.
  if recovered=$(omarchy-agent-account-state recover "$provider"); then
    if [[ $(jq 'length' <<<"$recovered") != "0" ]]; then
      announce_added "$recovered"
      exit 0
    fi
  else
    fail "$recovered"
  fi

  if [[ -z $label && $events == "false" && -t 0 ]]; then
    label=$(gum input --placeholder "Work" --prompt "Name this $name account: ") || exit 130
  fi

  if [[ $events == "true" ]]; then
    say "$(omarchy-i18n agents.signInPrivate)"
  else
    cat <<EOF

Sign in as the account you're adding in the private window that opens.
If a private window was already open, close it first, or $site may reuse whoever it has signed in.

Don't log out of the $name CLI to do this: logging out revokes the saved sign-in.

EOF
  fi

  home=$(omarchy-agent-account-state begin "$provider" "$label" "$$") || fail "$(omarchy-i18n agents.homeFailed)"

  private_browser
  interruptible env BROWSER="$browser" "$home_env=$home" "${login_command[@]}" 2>&1

  if account=$(omarchy-agent-account-state register "$provider" "$label" "$home" 2>&1); then
    home=""
    announce_added "[$account]"
  else
    registration_status=$?
    # Keep the home for cleanup when registration was explicitly interrupted.
    # Storage failures preserve the sign-in and receipt for the next refresh.
    if (( registration_status != 130 )); then
      home=""
    fi
    fail "$account"
  fi
fi
