#!/usr/bin/env bash
# egregore-launcher-version: 0.4.12
# egregore — launch an Egregore instance in Claude Code.
# Reads ~/.egregore/instances.json for the registry of installed egregores.
#
# Usage:
#   egregore                 pick an instance (or launch the only one)
#   egregore <slug|name>     launch the matching instance
#   egregore ls | list       list installed instances
#   egregore use <slug>      set the default for bare `egregore`
#   egregore prune           remove entries whose path is gone
#   egregore rm <slug|path>  remove a specific entry
#   egregore help | --help
#   egregore --version
#
# Installed by create-egregore. Safe to move or edit — persistent state lives
# only in ~/.egregore/instances.json and ~/.egregore/default.
#
# The first line's "egregore-launcher-version" comment is read by
# installLauncherBinary() so newer create-egregore installs can auto-upgrade
# a stale binary. Don't rename or remove it.

set -u

VERSION="0.4.12"
REGISTRY="${HOME}/.egregore/instances.json"
DEFAULT_FILE="${HOME}/.egregore/default"

# ── colors ────────────────────────────────────────────────────────
if [ -t 1 ] && [ -z "${NO_COLOR:-}" ]; then
  RESET=$'\e[0m'; BOLD=$'\e[1m'; DIM=$'\e[2m'
  CYAN=$'\e[36m'; GREEN=$'\e[32m'; YELLOW=$'\e[33m'; RED=$'\e[31m'
else
  RESET=""; BOLD=""; DIM=""; CYAN=""; GREEN=""; YELLOW=""; RED=""
fi

die() {
  printf '%segregore:%s %s\n' "$RED" "$RESET" "$*" >&2
  exit 1
}

banner() {
  printf '\n'
  printf '%s%s  ███████╗ ██████╗ ██████╗ ███████╗ ██████╗  ██████╗ ██████╗ ███████╗%s\n' "$BOLD" "$CYAN" "$RESET"
  printf '%s%s  ██╔════╝██╔════╝ ██╔══██╗██╔════╝██╔════╝ ██╔═══██╗██╔══██╗██╔════╝%s\n' "$BOLD" "$CYAN" "$RESET"
  printf '%s%s  █████╗  ██║  ███╗██████╔╝█████╗  ██║  ███╗██║   ██║██████╔╝█████╗%s\n'   "$BOLD" "$CYAN" "$RESET"
  printf '%s%s  ██╔══╝  ██║   ██║██╔══██╗██╔══╝  ██║   ██║██║   ██║██╔══██╗██╔══╝%s\n'   "$BOLD" "$CYAN" "$RESET"
  printf '%s%s  ███████╗╚██████╔╝██║  ██║███████╗╚██████╔╝╚██████╔╝██║  ██║███████╗%s\n' "$BOLD" "$CYAN" "$RESET"
  printf '%s%s  ╚══════╝ ╚═════╝ ╚═╝  ╚═╝╚══════╝ ╚═════╝  ╚═════╝ ╚═╝  ╚═╝╚══════╝%s\n' "$BOLD" "$CYAN" "$RESET"
  printf '\n'
}

require_jq() {
  command -v jq >/dev/null 2>&1 || die "jq is required but not installed (brew install jq)."
}

require_registry() {
  [ -f "$REGISTRY" ] || die "No egregores installed yet. Run: npx -y create-egregore@latest"
}

list_instances() {
  # Prints: <slug>\t<name>\t<path>
  jq -r '.[] | [.slug, .name, .path] | @tsv' "$REGISTRY"
}

instance_count() {
  jq 'length' "$REGISTRY"
}

resolve_instance() {
  # $1 = slug or name (fuzzy-ish: exact slug first, then exact name, then case-insensitive contains)
  local query="$1"
  local result
  result=$(jq -r --arg q "$query" '.[] | select(.slug == $q) | .path' "$REGISTRY" | head -n1)
  if [ -z "$result" ]; then
    result=$(jq -r --arg q "$query" '.[] | select(.name == $q) | .path' "$REGISTRY" | head -n1)
  fi
  if [ -z "$result" ]; then
    local qlower
    qlower=$(printf '%s' "$query" | tr '[:upper:]' '[:lower:]')
    result=$(jq -r --arg q "$qlower" '
      .[] | select((.slug | ascii_downcase | contains($q)) or (.name | ascii_downcase | contains($q))) | .path' "$REGISTRY" | head -n1)
  fi
  printf '%s' "$result"
}

# The SessionStart hook shows the startup card itself (bin/lib/card-delivery.sh),
# so Claude opens straight to the card and the prompt. Succeeds when the first
# screen still needs a model turn and `start` should be submitted: onboarding is
# pending, the framework is older, or jq is missing (the card then reaches the
# model as text to display). No state file, or an unreadable one, counts as
# onboarded, as in bin/session-start.sh.
claude_needs_start_prompt() {
  [ -f "$1/bin/lib/card-delivery.sh" ] || return 0
  command -v jq >/dev/null 2>&1 || return 0
  jq -e '(.onboarding_complete | tostring) != "true"' "$1/.egregore-state.json" >/dev/null 2>&1
}

launch() {
  local target_path="$1"
  local target_slug="${2:-}"
  [ -d "$target_path" ] || die "Instance path does not exist: $target_path"
  command -v claude >/dev/null 2>&1 || die "Claude Code is not installed. Install it from https://code.claude.com then try again."
  if [ -n "$target_slug" ]; then
    printf '  %s→%s launching %s%s%s ...\n\n' "$DIM" "$RESET" "$BOLD" "$target_slug" "$RESET"
  fi
  cd "$target_path" || die "Could not cd into $target_path"
  local -a claude_args=()
  claude_needs_start_prompt "$target_path" && claude_args=("start")
  # The greeting renders in-chat — no pre-launch card. Claude Code ≥2.1.89
  # boots into the alternate screen buffer, which hides anything printed
  # here; the launcher-card fast path is parked in PR #1493.
  exec claude ${claude_args[@]+"${claude_args[@]}"}
}

cmd_ls() {
  require_jq
  require_registry
  local default=""
  [ -f "$DEFAULT_FILE" ] && default=$(cat "$DEFAULT_FILE" 2>/dev/null)
  banner
  local count
  count=$(instance_count)
  local plural="s"
  [ "$count" -eq 1 ] && plural=""
  printf '  %s%d egregore%s registered%s\n\n' "$BOLD" "$count" "$plural" "$RESET"
  printf '    %s%-22s  %-24s  %s%s\n' "$DIM" "SLUG" "NAME" "PATH" "$RESET"
  while IFS=$'\t' read -r slug name path; do
    if [ "$slug" = "$default" ]; then
      printf '  %s●%s %s%-22s%s  %-24s  %s%s%s\n' "$GREEN" "$RESET" "$BOLD" "$slug" "$RESET" "$name" "$DIM" "$path" "$RESET"
    else
      printf '    %-22s  %-24s  %s%s%s\n' "$slug" "$name" "$DIM" "$path" "$RESET"
    fi
  done < <(list_instances)
  printf '\n'
  if [ -n "$default" ]; then
    printf '  %s●%s = default (bare %segregore%s launches this)\n\n' "$GREEN" "$RESET" "$BOLD" "$RESET"
  fi
}

cmd_use() {
  require_jq
  require_registry
  local slug="${1:-}"
  [ -n "$slug" ] || die "Usage: egregore use <slug>"
  local found
  found=$(jq -r --arg q "$slug" '.[] | select(.slug == $q) | .slug' "$REGISTRY" | head -n1)
  [ -n "$found" ] || die "No instance with slug '$slug'. Run: egregore ls"
  mkdir -p "$(dirname "$DEFAULT_FILE")"
  printf '%s\n' "$found" > "$DEFAULT_FILE"
  printf '  %s✓%s default set to %s%s%s\n' "$GREEN" "$RESET" "$BOLD" "$found" "$RESET"
}

# ── registry maintenance ─────────────────────────────────────────
#
# Atomic write: filter via jq to a tmp file, then rename. Backup every
# mutation to ~/.egregore/instances.json.bak.<timestamp> so a mis-click
# is always reversible.

backup_registry() {
  local ts
  ts=$(date +%Y%m%d-%H%M%S)
  local bak="${HOME}/.egregore/instances.json.bak.${ts}"
  cp "$REGISTRY" "$bak"
  printf '%s' "$bak"
}

cmd_prune() {
  require_jq
  require_registry
  banner

  # Collect stale entries (path doesn't exist on disk)
  local -a stale_slugs=()
  local -a stale_paths=()
  while IFS=$'\t' read -r slug path; do
    [ -d "$path" ] || { stale_slugs+=("$slug"); stale_paths+=("$path"); }
  done < <(jq -r '.[] | [.slug, .path] | @tsv' "$REGISTRY")

  local count_before count_stale
  count_before=$(instance_count)
  count_stale=${#stale_paths[@]}

  if [ "$count_stale" -eq 0 ]; then
    printf '  %s✓%s registry is clean — %d entries, all paths exist.\n\n' "$GREEN" "$RESET" "$count_before"
    return 0
  fi

  printf '  %s⚠%s %d of %d entries have missing paths:\n\n' "$YELLOW" "$RESET" "$count_stale" "$count_before"
  local i=0
  while [ "$i" -lt "$count_stale" ]; do
    printf '    %s✗%s %-22s %s%s%s\n' "$RED" "$RESET" "${stale_slugs[$i]}" "$DIM" "${stale_paths[$i]}" "$RESET"
    i=$((i + 1))
  done
  printf '\n'

  # Dry run short-circuit
  if [ "${1:-}" = "--dry-run" ] || [ "${1:-}" = "-n" ]; then
    printf '  %s(dry run — nothing removed. re-run without --dry-run to apply.)%s\n\n' "$DIM" "$RESET"
    return 0
  fi

  printf '  %s?%s remove them? [y/N]: ' "$CYAN" "$RESET"
  read -r confirm
  case "$confirm" in
    y|Y|yes|YES) ;;
    *) printf '  %sCancelled.%s\n\n' "$DIM" "$RESET"; return 0 ;;
  esac

  local bak
  bak=$(backup_registry)

  local tmp="${REGISTRY}.tmp.$$"
  # Keep only entries whose path still exists. The filesystem is the source
  # of truth — no path strings in the filter itself.
  jq '[.[] | select(.path as $p | ($p | @sh) as $_ | true)]' "$REGISTRY" > /dev/null 2>&1 || true
  # Actual filter: stream entries, read each path, bash test, emit if exists.
  # We rebuild the JSON array outside jq because jq can't check filesystem.
  {
    printf '['
    local first=1
    while IFS=$'\t' read -r slug name path; do
      if [ -d "$path" ]; then
        [ "$first" -eq 0 ] && printf ','
        jq -n --arg slug "$slug" --arg name "$name" --arg path "$path" \
          '{slug: $slug, name: $name, path: $path}' | jq -c .
        first=0
      fi
    done < <(jq -r '.[] | [.slug, .name, .path] | @tsv' "$REGISTRY")
    printf ']'
  } | jq '.' > "$tmp"

  mv "$tmp" "$REGISTRY"
  local count_after
  count_after=$(instance_count)
  printf '  %s✓%s pruned %d — %d remain.\n' "$GREEN" "$RESET" "$((count_before - count_after))" "$count_after"
  printf '  %sbackup:%s %s\n\n' "$DIM" "$RESET" "$bak"
}

cmd_rm() {
  require_jq
  require_registry
  local target="${1:-}"
  [ -n "$target" ] || die "Usage: egregore rm <slug-or-path>"

  # Find matches: exact slug, exact path, or substring match on either
  local matches
  matches=$(jq -r --arg q "$target" '
    .[] | select(.slug == $q or .path == $q or
                 (.slug | contains($q)) or (.path | contains($q)))
    | [.slug, .name, .path] | @tsv' "$REGISTRY")

  if [ -z "$matches" ]; then
    die "No instance matching '$target'. Run: egregore ls"
  fi

  local match_count
  match_count=$(printf '%s\n' "$matches" | wc -l | tr -d ' ')

  if [ "$match_count" -gt 1 ]; then
    printf '\n  %s⚠%s %d instances match %s"%s"%s:\n\n' "$YELLOW" "$RESET" "$match_count" "$BOLD" "$target" "$RESET"
    printf '%s\n' "$matches" | while IFS=$'\t' read -r slug name path; do
      printf '    %-22s  %-24s  %s%s%s\n' "$slug" "$name" "$DIM" "$path" "$RESET"
    done
    printf '\n  %sUse an exact path to pick one:%s\n' "$DIM" "$RESET"
    printf '    egregore rm <full-path>\n\n'
    exit 1
  fi

  local slug name path
  IFS=$'\t' read -r slug name path <<< "$matches"
  printf '\n  about to remove:\n'
  printf '    %-22s  %-24s  %s%s%s\n\n' "$slug" "$name" "$DIM" "$path" "$RESET"
  printf '  %s?%s confirm? [y/N]: ' "$CYAN" "$RESET"
  read -r confirm
  case "$confirm" in
    y|Y|yes|YES) ;;
    *) printf '  %sCancelled.%s\n\n' "$DIM" "$RESET"; return 0 ;;
  esac

  local bak
  bak=$(backup_registry)

  local tmp="${REGISTRY}.tmp.$$"
  jq --arg p "$path" '[.[] | select(.path != $p)]' "$REGISTRY" > "$tmp"
  mv "$tmp" "$REGISTRY"

  printf '  %s✓%s removed.\n' "$GREEN" "$RESET"
  printf '  %sbackup:%s %s\n\n' "$DIM" "$RESET" "$bak"
}

cmd_help() {
  banner
  printf '  %sUSAGE%s\n' "$BOLD" "$RESET"
  printf '    %segregore%s                    pick an instance (or launch the only one)\n' "$CYAN" "$RESET"
  printf '    %segregore %s<slug|name>%s        launch the matching instance\n' "$CYAN" "$DIM" "$RESET"
  printf '    %segregore ls%s                 list installed instances\n' "$CYAN" "$RESET"
  printf '    %segregore use %s<slug>%s         set the default for bare `egregore`\n' "$CYAN" "$DIM" "$RESET"
  printf '    %segregore prune%s              remove entries whose path is gone %s(--dry-run to preview)%s\n' "$CYAN" "$RESET" "$DIM" "$RESET"
  printf '    %segregore rm %s<slug-or-path>%s  remove a specific entry\n' "$CYAN" "$DIM" "$RESET"
  printf '    %segregore --help%s\n' "$CYAN" "$RESET"
  printf '    %segregore --version%s\n' "$CYAN" "$RESET"
  printf '\n  %sREGISTRY%s\n' "$BOLD" "$RESET"
  printf '    Instances live in ~/.egregore/instances.json (written by the installer).\n'
  printf '    Default selection lives in ~/.egregore/default.\n'
  printf '    Every mutation backs up to ~/.egregore/instances.json.bak.<timestamp>.\n\n'
}

# ── picker ────────────────────────────────────────────────────────
#
# Shown when the user runs bare `egregore` with multiple instances and no
# default set. Numbered list + prompt that accepts numeric or slug input.

picker() {
  banner
  printf '  %s◆%s pick an instance to launch:\n\n' "$CYAN" "$RESET"
  local -a slug_arr=()
  local -a path_arr=()
  local -a name_arr=()
  while IFS=$'\t' read -r slug name path; do
    slug_arr+=("$slug")
    path_arr+=("$path")
    name_arr+=("$name")
  done < <(list_instances)

  local default=""
  [ -f "$DEFAULT_FILE" ] && default=$(cat "$DEFAULT_FILE" 2>/dev/null)

  local idx=1
  for slug in "${slug_arr[@]}"; do
    local marker="  "
    [ "$slug" = "$default" ] && marker="${GREEN}●${RESET} "
    printf '    %s%2d)%s %s  %s%-22s%s  %s%s%s\n' \
      "$DIM" "$idx" "$RESET" "$marker" "$BOLD" "$slug" "$RESET" "$DIM" "${name_arr[$((idx-1))]}" "$RESET"
    idx=$((idx + 1))
  done
  printf '\n'
  printf '  %s?%s enter number or slug: ' "$CYAN" "$RESET"
  read -r choice
  [ -n "$choice" ] || die "No selection."

  # Numeric choice
  if printf '%s' "$choice" | grep -Eq '^[0-9]+$'; then
    local chosen_idx=$((choice - 1))
    if [ "$chosen_idx" -ge 0 ] && [ "$chosen_idx" -lt "${#path_arr[@]}" ]; then
      launch "${path_arr[$chosen_idx]}" "${slug_arr[$chosen_idx]}"
    fi
    die "Invalid selection: $choice"
  fi

  # Non-numeric: treat as slug/name
  local target
  target=$(resolve_instance "$choice")
  [ -n "$target" ] || die "No instance matching '$choice'."
  launch "$target" "$choice"
}

# ── main ──────────────────────────────────────────────────────────

case "${1:-}" in
  --help|-h|help) cmd_help; exit 0 ;;
  --version|-V|version) echo "egregore $VERSION"; exit 0 ;;
  ls|list) shift; cmd_ls "$@"; exit 0 ;;
  use) shift; cmd_use "$@"; exit 0 ;;
  prune) shift; cmd_prune "$@"; exit 0 ;;
  rm|remove) shift; cmd_rm "$@"; exit 0 ;;
esac

require_jq
require_registry

count=$(instance_count)

if [ "$count" -eq 0 ]; then
  die "No egregores installed yet. Run: npx -y create-egregore@latest"
fi

# Explicit instance requested — fast path, no banner
if [ $# -gt 0 ]; then
  target=$(resolve_instance "$1")
  [ -n "$target" ] || die "No instance matching '$1'. Run: egregore ls"
  launch "$target" "$1"
fi

# No args — use default if set, or only instance, else picker
if [ -f "$DEFAULT_FILE" ]; then
  default_slug=$(cat "$DEFAULT_FILE" 2>/dev/null)
  if [ -n "$default_slug" ]; then
    target=$(jq -r --arg q "$default_slug" '.[] | select(.slug == $q) | .path' "$REGISTRY" | head -n1)
    if [ -n "$target" ]; then
      launch "$target" "$default_slug"
    fi
  fi
fi

if [ "$count" -eq 1 ]; then
  target=$(jq -r '.[0].path' "$REGISTRY")
  slug=$(jq -r '.[0].slug' "$REGISTRY")
  launch "$target" "$slug"
fi

picker
