#!/bin/bash

# omarchy:summary=Regenerate the AI agent usage data files
# omarchy:args=[--force] [--limits-only] [--except <agent>] [agent...]
# omarchy:examples=omarchy agent usage-update | omarchy agent usage-update claude | omarchy agent usage-update --except codex

# Each omarchy-agent-usage-<agent> collector prints one display-ready JSON
# record; this writes them to ~/.local/state/omarchy/agents/usage/ where the
# agents panel watches them. Adding an agent is adding a collector — the
# panel picks up any record that appears here.

USAGE_DIR="${XDG_STATE_HOME:-$HOME/.local/state}/omarchy/agents/usage"
mkdir -p "$USAGE_DIR"

flags=()
only=()
declare -A excluded

while (( $# > 0 )); do
  case "$1" in
  --force | --limits-only) flags+=("$1") ;;
  --except)
    if [[ -z ${2:-} ]]; then
      echo "--except needs an agent" >&2
      exit 1
    else
      excluded[$2]=1
      shift
    fi
    ;;
  *) only+=("$1") ;;
  esac
  shift
done

wanted() {
  local agent="$1"
  [[ -n ${excluded[$agent]} ]] && return 1
  (( ${#only[@]} == 0 )) && return 0
  local candidate
  for candidate in "${only[@]}"; do
    [[ $candidate == "$agent" ]] && return 0
  done
  return 1
}

collect() {
  local collector="$1" agent="$2"
  local record tmp
  # Two collectors still compete with a foreground using every thread, so each
  # takes only spare CPU and disk time. The alert below holds a lock, so not it.
  chrt --idle -p 0 $BASHPID 2>/dev/null
  ionice -c 3 -p $BASHPID 2>/dev/null
  if ! record=$("$collector" "${flags[@]}") || [[ -z $record ]] || ! jq -e . >/dev/null 2>&1 <<<"$record"; then
    echo "omarchy-agent-usage-update: $agent collector failed" >&2
    return 1
  fi
  tmp=$(mktemp "$USAGE_DIR/.$agent.XXXXXX")
  printf '%s\n' "$record" >"$tmp"
  mv "$tmp" "$USAGE_DIR/$agent.json"
}

# Accounts can be signed in to someone else since they were added; the
# records name them from the registry, so bring it up to date first.
accounts_dir="${XDG_STATE_HOME:-$HOME/.local/state}/omarchy/agents/accounts"
if [[ -d $accounts_dir ]]; then
  "$OMARCHY_PATH/bin/omarchy-agent-account-state" refresh
fi

# Collectors forced together read the Codex rollouts they share once between
# them, whenever each gets to them, by knowing when this refresh began.
# EPOCHREALTIME uses the locale's decimal separator, a comma in many.
export OMARCHY_AGENT_USAGE_REFRESH_AT=${EPOCHREALTIME/,/.}

# Every collector re-scans local session stores, and all of them at once pin
# every core for the whole scan, so they take turns, two at a time.
max_jobs=2

pids=()
for collector in "$OMARCHY_PATH"/bin/omarchy-agent-usage-*; do
  [[ -x $collector ]] || continue
  agent="${collector##*/omarchy-agent-usage-}"
  [[ $agent == "update" ]] && continue
  wanted "$agent" || continue
  # wait -n only frees a slot; each status is read from its own pid below.
  while (( $(jobs -pr | wc -l) >= max_jobs )); do
    wait -n
  done
  collect "$collector" "$agent" &
  pids+=($!)
done

status=0
for pid in "${pids[@]}"; do
  wait "$pid" || status=1
done

# Fresh limits are when an account near a limit gets announced.
for agent in claude codex grok; do
  if wanted "$agent" && [[ -f $accounts_dir/$agent.json ]]; then
    "$OMARCHY_PATH/bin/omarchy-agent-account-state" alert "$agent"
  fi
done

exit $status
