#!/usr/bin/env bash
# Run blumkin from this checkout (or any worktree of it) with no install step.
#
# It runs the in-repo code against the real config directory, keychain entries, token cache
# and agent state, so what you see is what the installed `blumkin` would do with this code.
# `--version` carries a `+dev.<sha>.<date>` marker (plus `-dirty`) so you can tell which code
# ran. Point BLUMKIN_CONFIG_DIR at an empty directory for a throwaway setup.
#
# If the config directory has no config.toml, a terminal gets an offer to run the guided
# `auth setup`; without a terminal this fails with a hint. Nothing is created or overwritten
# unless you say yes.
set -euo pipefail

# Tells blumkin this is a dev run: `--version`, `doctor` and the MCP server then carry the
# `+dev.<sha>.<date>` marker. A plain editable install does not.
export BLUMKIN_DEV=1

resolve_path() {
  local path="$1" directory
  while [[ -L "${path}" ]]; do
    directory="$(cd "$(dirname "${path}")" && pwd -P)"
    path="$(readlink "${path}")"
    [[ "${path}" == /* ]] || path="${directory}/${path}"
  done
  printf '%s/%s\n' "$(cd "$(dirname "${path}")" && pwd -P)" "$(basename "${path}")"
}

script_path="$(resolve_path "${BASH_SOURCE[0]}")"
repo_root="$(cd "$(dirname "${script_path}")/../.." && pwd -P)"
readonly script_path repo_root
# So `mcp install` run through this launcher registers the launcher itself.
export BLUMKIN_DEV_LAUNCHER="${script_path}"

if ! command -v uv >/dev/null 2>&1; then
  echo "blumkin (dev): uv is required but was not found on PATH" >&2
  exit 127
fi

run_blumkin() {
  uv run --frozen --project "${repo_root}" blumkin "$@"
}

# `value` without leading and trailing whitespace (Python strips these env values too).
trim() {
  printf '%s' "$1" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//'
}

# Mirrors blumkin.config.config_dir(): BLUMKIN_CONFIG_DIR, then XDG_CONFIG_HOME, then ~/.config.
# Blank values count as unset, and a leading ~ or ~/ is expanded (not ~user, like a plain ~/).
config_dir() {
  local chosen override xdg
  override="${BLUMKIN_CONFIG_DIR:-}"
  xdg="${XDG_CONFIG_HOME:-}"
  override="$(trim "${override}")"
  xdg="$(trim "${xdg}")"
  if [[ -n "${override}" ]]; then
    chosen="${override}"
  elif [[ -n "${xdg}" ]]; then
    chosen="${xdg}/blumkin"
  else
    chosen="${HOME}/.config/blumkin"
  fi
  if [[ "${chosen}" == "~" ]]; then
    chosen="${HOME}"
  elif [[ "${chosen}" == \~/* ]]; then
    chosen="${HOME}/${chosen:2}"
  fi
  printf '%s\n' "${chosen}"
}

# Whether the command needs a config.toml. The provider-bound commands do (mail, calendar,
# chat, drive, docs, people, meeting, tasks, capabilities, doctor, `auth` apart from `auth
# setup`, and `mcp serve`), and so do the ones that create state under the config directory
# or act on a profile (`browser`, `loop`, `receipts`): they keep the friendly setup hint, and
# the launcher never creates anything unless the user says yes. The rest answer for
# themselves without one: help, version, `profiles`, `completion`, `agent`, `mcp install` and
# `mcp status`, `skills`, `upgrade`. `-h` is not help: blumkin only accepts `--help`. A new
# command that is exempt by default and needs a profile fails with Python's own error, not
# this hint, so add it to the list below.
needs_config() {
  local arg previous="" positional=()
  for arg in "$@"; do
    case "${arg}" in
      --help | --version) return 1 ;;
    esac
    if [[ "${arg}" != -* && "${previous}" != "--profile" && "${previous}" != "--tz" ]]; then
      positional+=("${arg}")
    fi
    previous="${arg}"
  done
  case "${positional[0]:-}" in
    browser | calendar | capabilities | chat | doctor | docs | drive | loop | mail | meeting | \
      people | receipts | tasks)
      return 0
      ;;
    auth)
      [[ "${positional[1]:-}" == "setup" ]] && return 1
      return 0
      ;;
    mcp)
      [[ "${positional[1]:-}" == "serve" ]] && return 0
      return 1
      ;;
    *) return 1 ;;
  esac
}

# The --profile option (either `--profile X` or `--profile=X`), so the guided setup configures
# the profile being run.
profile_arguments() {
  local arg previous=""
  for arg in "$@"; do
    if [[ "${previous}" == "--profile" ]]; then
      printf '%s\n' "--profile" "${arg}"
      return
    fi
    if [[ "${arg}" == --profile=* ]]; then
      printf '%s\n' "${arg}"
      return
    fi
    previous="${arg}"
  done
}

if needs_config "$@"; then
  directory="$(config_dir)"
  if [[ ! -f "${directory}/config.toml" ]]; then
    echo "blumkin (dev): no config.toml in ${directory}" >&2
    if [[ -t 0 && -t 1 ]]; then
      answer=""
      read -r -p "Run the guided setup now (creates ${directory}/config.toml)? [y/N] " answer || true
      if [[ "${answer}" =~ ^[Yy] ]]; then
        # Written for bash 3.2 (macOS): no mapfile, and an empty array needs the + guard.
        setup_profile=()
        while IFS= read -r line; do
          setup_profile+=("${line}")
        done < <(profile_arguments "$@")
        run_blumkin ${setup_profile[@]+"${setup_profile[@]}"} auth setup
      else
        echo "Run it yourself when ready: scripts/dev/blumkin auth setup" >&2
        exit 2
      fi
    else
      echo "Run on a terminal: scripts/dev/blumkin auth setup" >&2
      echo "or without one: scripts/dev/blumkin auth setup --yes --provider google|microsoft" \
        "plus the value flags (see: scripts/dev/blumkin auth setup --help)" >&2
      exit 2
    fi
  fi
fi

exec uv run --frozen --project "${repo_root}" blumkin "$@"
