#!/usr/bin/env bash
set -euo pipefail

CHAT_ID="${1:-}"
PACKAGE="${CIRCUIT_CLI_PACKAGE:-@circuitorg/agent-cli}"
ORIGINAL_PATH="$PATH"


fail() {
  printf 'error: %s\n' "$*" >&2
  exit 1
}

path_has_entry() {
  local bin_dir="$1"
  local path_value="${2:-$PATH}"

  case ":${path_value}:" in
    *:"$bin_dir":*) return 0 ;;
    *) return 1 ;;
  esac
}

prepend_path_once() {
  local bin_dir="$1"

  if [[ -z "$bin_dir" ]]; then
    return
  fi

  if ! path_has_entry "$bin_dir"; then
    export PATH="$bin_dir:$PATH"
  fi
}

persist_zsh_path_entry() {
  local bin_dir="$1"
  local original_path="$2"

  if [[ -z "${HOME:-}" || -z "$bin_dir" ]]; then
    return
  fi

  if path_has_entry "$bin_dir" "$original_path"; then
    return
  fi

  local marker_start="# >>> Circuit CLI Bun global bin >>>"
  local marker_end="# <<< Circuit CLI Bun global bin <<<"
  local path_block
  path_block="$(cat <<EOF
$marker_start
# Added by the Circuit CLI installer so zsh can resolve 'circuit'.
case ":\$PATH:" in
  *:"$bin_dir":*) ;;
  *) export PATH="$bin_dir:\$PATH" ;;
esac
$marker_end
EOF
)"

  local profile
  for profile in "$HOME/.zprofile" "$HOME/.zshrc"; do
    if [[ -f "$profile" ]] && grep -Fq "$marker_start" "$profile"; then
      continue
    fi

    touch "$profile"
    if [[ -s "$profile" ]]; then
      printf '\n' >> "$profile"
    fi
    printf '%s\n' "$path_block" >> "$profile"
  done
}

install_with_bun() {
  local bin_dir
  bin_dir="$(bun pm bin -g)"
  persist_zsh_path_entry "$bin_dir" "$ORIGINAL_PATH"
  prepend_path_once "$bin_dir"
  bun install -g "$PACKAGE"
}

ensure_bun() {
  if command -v bun >/dev/null 2>&1; then
    return
  fi
  curl -fsSL https://bun.com/install | bash
  export BUN_INSTALL="${BUN_INSTALL:-$HOME/.bun}"
  export PATH="$BUN_INSTALL/bin:$PATH"
  command -v bun >/dev/null 2>&1 || fail "Bun installed, but 'bun' is not on PATH. Restart your shell and rerun the command."
}

ensure_bun
install_with_bun

if ! command -v circuit >/dev/null 2>&1; then
  fail "Circuit CLI installed, but 'circuit' is not on PATH. Restart your shell and rerun the command."
fi

if [[ -n "$CHAT_ID" ]]; then
  circuit auth login
  circuit pull "$CHAT_ID"
fi
