#!/usr/bin/env bash
#
# Archie -> Cursor integration installer.
#
# Registers selected Archie MCP environments with Cursor (user-level
# ~/.cursor/mcp.json, or a project-level .cursor/mcp.json), installs the Archie
# agent skills into ~/.cursor/skills/, and optionally drops the Archie guideline
# rule into a project so Cursor's agent knows when and how to drive Archie.
#
# Interactive mode registers archie-prod by default; archie-local and
# archie-nonprod are opt-in. Non-interactive mode defaults to prod only unless
# ARCHIE_INSTALL_ENVS or per-environment opt-in flags/tokens are set.
#
# Cursor talks to Archie over the official MCP streamable-HTTP transport on the
# MCP service (port 8081 locally; public API Gateway in nonprod/prod) at
# <base>/mcp/stream/. Connectivity is verified by calling listRepositories on
# the JSON MCP surface at <base>/mcp/call.
#
# Usage (interactive):
#   ./integrations/cursor/install.sh
#
# Usage (remote install — no clone required):
#   curl -fsSL https://archie-install.lonelyplanet.com/install.sh | bash
#
# Override the asset base URL when mirroring Bito-style hosting:
#   ARCHIE_CDN_URL="https://example.com/cursor" curl -fsSL .../install.sh | bash
# Usage (non-interactive / CI):
#   ARCHIE_TOKEN_PROD="<bearer>" ./integrations/cursor/install.sh --non-interactive
#   ARCHIE_INSTALL_ENVS="prod,nonprod" ARCHIE_TOKEN_NONPROD="<bearer>" \
#     ./integrations/cursor/install.sh --non-interactive
#
# Flags:
#   --non-interactive     Read tokens from env (ARCHIE_TOKEN_LOCAL,
#                         ARCHIE_TOKEN_NONPROD, ARCHIE_TOKEN_PROD). Defaults to
#                         prod only; set ARCHIE_INSTALL_ENVS and/or
#                         ARCHIE_INSTALL_LOCAL / ARCHIE_INSTALL_NONPROD to add
#                         environments. Supplying ARCHIE_TOKEN_LOCAL or
#                         ARCHIE_TOKEN_NONPROD also opts those environments in.
#   --project DIR         Also write DIR/.cursor/mcp.json and the guideline rule
#                         into DIR (project-scoped install). Tokens are NOT written
#                         to a project file; project scope uses ${env:ARCHIE_TOKEN_*}.
#   --no-skills           Skip installing skills into ~/.cursor/skills/.
#
set -euo pipefail

# --- pretty output -----------------------------------------------------------
if [[ -t 1 ]]; then
  RED=$'\033[0;31m'; GREEN=$'\033[0;32m'; YELLOW=$'\033[1;33m'; BLUE=$'\033[0;34m'; NC=$'\033[0m'
else
  RED=""; GREEN=""; YELLOW=""; BLUE=""; NC=""
fi
info()    { echo "${BLUE}i ${NC}$*"; }
ok()      { echo "${GREEN}✓ ${NC}$*"; }
warn()    { echo "${YELLOW}! ${NC}$*"; }
err()     { echo "${RED}✗ ${NC}$*" >&2; }

SCRIPT_DIR=""
CDN_BASE_URL="${ARCHIE_CDN_URL:-https://archie-install.lonelyplanet.com}"
RUNNING_FROM_CDN=false
GUIDELINES_FILE=""
SKILLS_BASE_DIR=""

# Skill names used when manifest.json is unavailable.
ARCHIE_SKILL_NAMES=(
  archie-feature-plan
  archie-epic-plan
  archie-workstreams
  archie-epic-workstreams
)
ENV_NAMES=(archie-local archie-nonprod archie-prod)
ENV_DEFAULT_URLS=(
  "http://localhost:8081"
  "https://data.nonprod.lonelyplanet.com/archie"
  "https://data.prod.lonelyplanet.com/archie"
)
ENV_TOKEN_VARS=(ARCHIE_TOKEN_LOCAL ARCHIE_TOKEN_NONPROD ARCHIE_TOKEN_PROD)
ENV_URL_VARS=(ARCHIE_URL_LOCAL ARCHIE_URL_NONPROD ARCHIE_URL_PROD)
ENV_PROJECT_TOKEN_VARS=(ARCHIE_TOKEN_LOCAL ARCHIE_TOKEN_NONPROD ARCHIE_TOKEN_PROD)

declare -a ENV_BASE_URLS=()
declare -a ENV_MCP_URLS=()
declare -a ENV_TOKENS=()
declare -a ENV_SELECTED_INDICES=()

# --- args --------------------------------------------------------------------
NON_INTERACTIVE=false
PROJECT_DIR=""
INSTALL_SKILLS=true
while [[ $# -gt 0 ]]; do
  case "$1" in
    --non-interactive) NON_INTERACTIVE=true ;;
    --project) PROJECT_DIR="${2:-}"; shift ;;
    --project=*) PROJECT_DIR="${1#*=}" ;;
    --no-skills) INSTALL_SKILLS=false ;;
    -h|--help) sed -n '2,30p' "$0"; exit 0 ;;
    *) warn "ignoring unknown argument: $1" ;;
  esac
  shift
done

# --- helpers -----------------------------------------------------------------
have_jq() { command -v jq >/dev/null 2>&1; }
have_curl() { command -v curl >/dev/null 2>&1; }

cdn_fetch() {
  local dest="$1" url="$2"
  have_curl || { err "curl is required for remote install"; return 1; }
  mkdir -p "$(dirname "$dest")"
  curl -sfL --max-time 30 "$url" -o "$dest"
}

detect_script_mode() {
  SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]:-}")" 2>/dev/null && pwd)" || SCRIPT_DIR=""
  GUIDELINES_FILE=""
  SKILLS_BASE_DIR=""
  RUNNING_FROM_CDN=false

  if [[ -n "$SCRIPT_DIR" && -f "$SCRIPT_DIR/ArchieGuidelines.md" ]]; then
    GUIDELINES_FILE="$SCRIPT_DIR/ArchieGuidelines.md"
  elif [[ -f "./ArchieGuidelines.md" ]]; then
    GUIDELINES_FILE="$(pwd)/ArchieGuidelines.md"
  fi

  if [[ -n "$SCRIPT_DIR" && -d "$SCRIPT_DIR/skills" ]]; then
    SKILLS_BASE_DIR="$SCRIPT_DIR/skills"
  elif [[ -d "./skills" ]]; then
    SKILLS_BASE_DIR="$(pwd)/skills"
  fi

  if [[ -z "$SKILLS_BASE_DIR" ]]; then
    RUNNING_FROM_CDN=true
    info "Running from remote install bundle ($CDN_BASE_URL)"
  fi
}

install_skills() {
  local SKILLS_DEST="$HOME/.cursor/skills"
  mkdir -p "$SKILLS_DEST"

  if [[ "$RUNNING_FROM_CDN" == "true" ]]; then
    local manifest_url="$CDN_BASE_URL/skills/manifest.json"
    local manifest_file
    manifest_file="$(mktemp "${TMPDIR:-/tmp}/archie-skills-manifest.XXXXXX")"
    if cdn_fetch "$manifest_file" "$manifest_url" && have_jq; then
      local names paths name path dest
      names=($(jq -r '.skills[].name' "$manifest_file"))
      paths=($(jq -r '.skills[].path' "$manifest_file"))
      rm -f "$manifest_file"
      local i
      for i in "${!names[@]}"; do
        name="${names[$i]}"
        path="${paths[$i]}"
        dest="$SKILLS_DEST/$name"
        mkdir -p "$dest"
        cdn_fetch "$dest/SKILL.md" "$CDN_BASE_URL/$path"
        ok "Installed skill: $name -> $dest (from CDN)"
      done
      return 0
    fi
    rm -f "$manifest_file"
    warn "Could not load skills/manifest.json from CDN; installing known skills directly."
    local name dest
    for name in "${ARCHIE_SKILL_NAMES[@]}"; do
      dest="$SKILLS_DEST/$name"
      mkdir -p "$dest"
      cdn_fetch "$dest/SKILL.md" "$CDN_BASE_URL/skills/$name/SKILL.md"
      ok "Installed skill: $name -> $dest (from CDN)"
    done
    return 0
  fi

  for skill_dir in "$SKILLS_BASE_DIR"/*/; do
    [[ -d "$skill_dir" ]] || continue
    local name
    name="$(basename "$skill_dir")"
    [[ "$name" == "manifest.json" ]] && continue
    rm -rf "$SKILLS_DEST/$name"
    cp -R "$skill_dir" "$SKILLS_DEST/$name"
    ok "Installed skill: $name -> $SKILLS_DEST/$name"
  done
}

install_guideline_rule() {
  local rules_file="$1"
  local guidelines_tmp=""
  mkdir -p "$(dirname "$rules_file")"

  if [[ -n "$GUIDELINES_FILE" && -f "$GUIDELINES_FILE" ]]; then
    :
  elif [[ "$RUNNING_FROM_CDN" == "true" ]]; then
    guidelines_tmp="$(mktemp "${TMPDIR:-/tmp}/archie-guidelines.XXXXXX")"
    if ! cdn_fetch "$guidelines_tmp" "$CDN_BASE_URL/ArchieGuidelines.md"; then
      warn "Could not download ArchieGuidelines.md from CDN; skipping guideline rule."
      rm -f "$guidelines_tmp"
      return 0
    fi
    GUIDELINES_FILE="$guidelines_tmp"
  else
    return 0
  fi

  {
    echo "---"
    echo "description: How and when to use the Archie MCP server (a plan-only AI architect)."
    echo "alwaysApply: false"
    echo "---"
    echo ""
    cat "$GUIDELINES_FILE"
  } > "$rules_file"
  [[ -n "$guidelines_tmp" ]] && rm -f "$guidelines_tmp"
  ok "Installed guideline rule: $rules_file"
}

# --- environment definitions -------------------------------------------------
normalize_env_url() {
  local idx="$1" raw="$2"
  local base stream

  base="${raw%/}"
  if [[ ! "$base" =~ ^https?:// ]]; then
    err "URL must start with http:// or https:// (got: $base)"; exit 2
  fi
  case "$base" in
    */mcp/stream) stream="$base"; base="${base%/mcp/stream}" ;;
    */mcp)        stream="$base/stream"; base="${base%/mcp}" ;;
    *)            stream="$base/mcp/stream" ;;
  esac
  ENV_BASE_URLS[$idx]="$base"
  ENV_MCP_URLS[$idx]="$stream/"
}

resolve_env_urls() {
  local i url_var
  ENV_BASE_URLS=()
  ENV_MCP_URLS=()
  for i in "${!ENV_NAMES[@]}"; do
    url_var="${ENV_URL_VARS[$i]}"
    normalize_env_url "$i" "${!url_var:-${ENV_DEFAULT_URLS[$i]}}"
  done
}

token_hint() {
  local name="$1"
  case "$name" in
    archie-local)
      echo "Local default is dev-local-token (see make dev / LOCAL_EVAL.md)."
      ;;
    archie-nonprod)
      echo "Nonprod token: jq -r '.sensitive.ARCHIE_BEARER_TOKEN' deploy/kubernetes/envvars.nonprod.json"
      ;;
    archie-prod)
      echo "Prod token: jq -r '.sensitive.ARCHIE_BEARER_TOKEN' deploy/kubernetes/envvars.prod.json"
      ;;
  esac
}

env_index() {
  local target="$1" i
  for i in "${!ENV_NAMES[@]}"; do
    [[ "${ENV_NAMES[$i]}" == "$target" ]] && { echo "$i"; return 0; }
  done
  return 1
}

index_selected() {
  local idx="$1" i
  (( ${#ENV_SELECTED_INDICES[@]} )) || return 1
  for i in "${ENV_SELECTED_INDICES[@]}"; do
    [[ "$i" == "$idx" ]] && return 0
  done
  return 1
}

add_selected_index() {
  local idx="$1" i
  index_selected "$idx" && return 0
  ENV_SELECTED_INDICES+=("$idx")
}

sort_selected_indices() {
  (( ${#ENV_SELECTED_INDICES[@]} )) || return 0
  ENV_SELECTED_INDICES=($(printf '%s\n' "${ENV_SELECTED_INDICES[@]}" | sort -n | uniq))
}

parse_install_envs_spec() {
  local spec="$1" part
  ENV_SELECTED_INDICES=()
  spec="${spec// /}"
  if [[ -z "$spec" ]]; then
    add_selected_index 2
    return
  fi
  IFS=',' read -r -a parts <<< "$spec"
  for part in "${parts[@]}"; do
    case "$part" in
      local|archie-local) add_selected_index 0 ;;
      nonprod|archie-nonprod) add_selected_index 1 ;;
      prod|archie-prod) add_selected_index 2 ;;
      *)
        err "Unknown environment in ARCHIE_INSTALL_ENVS: $part (use local, nonprod, prod)"
        exit 2
        ;;
    esac
  done
  sort_selected_indices
  [[ ${#ENV_SELECTED_INDICES[@]} -gt 0 ]] || { err "ARCHIE_INSTALL_ENVS matched no environments"; exit 2; }
}

prompt_yes_no() {
  local prompt="$1" default_no="${2:-true}" answer
  if [[ "$default_no" == "true" ]]; then
    read -r -p "$prompt [y/N] " answer < /dev/tty
    [[ "$answer" =~ ^[Yy] ]]
  else
    read -r -p "$prompt [Y/n] " answer < /dev/tty
    [[ -z "$answer" || "$answer" =~ ^[Yy] ]]
  fi
}

select_environments() {
  resolve_env_urls
  ENV_SELECTED_INDICES=()

  if [[ "$NON_INTERACTIVE" == "true" ]]; then
    if [[ -n "${ARCHIE_INSTALL_ENVS:-}" ]]; then
      parse_install_envs_spec "$ARCHIE_INSTALL_ENVS"
    else
      add_selected_index 2
      [[ "${ARCHIE_INSTALL_LOCAL:-}" == "true" || -n "${ARCHIE_TOKEN_LOCAL:-}" ]] && add_selected_index 0
      [[ "${ARCHIE_INSTALL_NONPROD:-}" == "true" || -n "${ARCHIE_TOKEN_NONPROD:-}" ]] && add_selected_index 1
      sort_selected_indices
    fi
    return
  fi

  echo "Select Archie MCP environments to register in Cursor."
  echo "archie-prod is included by default."
  echo ""

  add_selected_index 2
  if prompt_yes_no "Also register archie-local (${ENV_DEFAULT_URLS[0]})?"; then
    add_selected_index 0
  fi
  if prompt_yes_no "Also register archie-nonprod (${ENV_DEFAULT_URLS[1]})?"; then
    add_selected_index 1
  fi
  sort_selected_indices

  echo ""
  info "Will register:"
  local i
  for i in "${ENV_SELECTED_INDICES[@]}"; do
    echo "  - ${ENV_NAMES[$i]}  ${ENV_DEFAULT_URLS[$i]}"
  done
  echo ""
}

warn_missing_token() {
  local name="$1" token="$2"
  [[ -n "$token" ]] && return 0
  warn "$name: no bearer token configured — MCP will fail until you add one."
  info "  $(token_hint "$name")"
}

# --- collect config ----------------------------------------------------------
collect_tokens() {
  local i name token_var token
  ENV_TOKENS=()
  for i in "${!ENV_NAMES[@]}"; do
    ENV_TOKENS[$i]=""
  done

  if [[ "$NON_INTERACTIVE" == "true" ]]; then
    for i in "${ENV_SELECTED_INDICES[@]}"; do
      token_var="${ENV_TOKEN_VARS[$i]}"
      ENV_TOKENS[$i]="${!token_var:-}"
      warn_missing_token "${ENV_NAMES[$i]}" "${ENV_TOKENS[$i]}"
    done
    return
  fi

  echo "Configure bearer tokens for the selected environments."
  echo "(Press Enter to skip a token — the server entry will still be registered.)"
  echo ""

  for i in "${ENV_SELECTED_INDICES[@]}"; do
    name="${ENV_NAMES[$i]}"
    echo "$name  ${ENV_BASE_URLS[$i]}"
    info "  $(token_hint "$name")"
    read -r -s -p "  Bearer token (Enter to skip): " token < /dev/tty
    echo ""
    ENV_TOKENS[$i]="$token"
    warn_missing_token "$name" "$token"
    echo ""
  done
}

connection_hint() {
  local name="$1"
  case "$name" in
    archie-local)   echo "dev server running?" ;;
    archie-nonprod) echo "bearer token required?" ;;
    archie-prod)    echo "bearer token required? Env not live yet?" ;;
    *)              echo "server reachable?" ;;
  esac
}

http_code() {
  local url="$1"
  shift
  local code
  code=$(curl -s -o /dev/null -w "%{http_code}" --max-time 8 "$url" "$@" 2>/dev/null || true)
  [[ -z "$code" ]] && code="000"
  printf '%s' "$code"
}

count_repos_from_call() {
  local body="$1"
  if have_jq; then
    printf '%s' "$body" | jq -r 'if (.result | type) == "array" then (.result | length) else empty end' 2>/dev/null || true
    return 0
  fi
  if command -v python3 >/dev/null 2>&1; then
    printf '%s' "$body" | python3 -c 'import json,sys; d=json.load(sys.stdin); r=d.get("result"); print(len(r) if isinstance(r,list) else "")' 2>/dev/null || true
  fi
  return 0
}

token_setup_hint() {
  local name="$1" project_token_var
  if [[ -n "$PROJECT_DIR" ]]; then
    project_token_var="${ENV_PROJECT_TOKEN_VARS[$(env_index "$name")]}"
    info "  Export ${project_token_var} before launching Cursor, or re-run without --project"
  else
    info "  Re-run the installer and paste the token, or edit ~/.cursor/mcp.json"
  fi
}

# --- MCP connectivity probe (informational only, never block) ----------------
probe_mcp() {
  local name="$1" base="$2" token="$3"
  local hint code body count response curl_args=()

  if ! have_curl; then
    warn "  curl not found; skipping MCP connection probe."
    return 0
  fi

  hint="$(connection_hint "$name")"

  if [[ -z "$token" ]]; then
    code="$(http_code "$base/mcp/tools")"
    case "$code" in
      200) ;; # auth disabled server-side; listRepositories may work without a token
      401|403)
        warn "  MCP probe skipped — bearer token required (HTTP $code without one)"
        token_setup_hint "$name"
        return 0
        ;;
      000)
        warn "  MCP probe skipped — server unreachable ($hint)"
        return 0
        ;;
      *)
        warn "  MCP probe: unexpected HTTP $code from /mcp/tools — configured anyway"
        return 0
        ;;
    esac
  fi

  curl_args=(-s -w $'\n%{http_code}' --max-time 15 -X POST "$base/mcp/call"
    -H "Content-Type: application/json"
    -d '{"name":"listRepositories","arguments":{}}')
  [[ -n "$token" ]] && curl_args+=(-H "Authorization: Bearer $token")

  response="$(curl "${curl_args[@]}" 2>/dev/null || true)"
  code="${response##*$'\n'}"
  body="${response%$'\n'$code}"

  case "$code" in
    200)
      count="$(count_repos_from_call "$body" || true)"
      if [[ -n "$count" && "$count" =~ ^[0-9]+$ ]]; then
        ok "  Connected — listRepositories returned $count indexed repo(s)"
      else
        ok "  Connected — listRepositories succeeded"
      fi
      ;;
    401|403)
      if [[ -n "$token" ]]; then
        err "  listRepositories rejected bearer token (HTTP $code) — check ARCHIE_BEARER_TOKEN on the server"
      else
        warn "  listRepositories requires a bearer token (HTTP $code)"
        token_setup_hint "$name"
      fi
      ;;
    000)
      warn "  Could not reach MCP — configured anyway ($hint)"
      ;;
    *)
      warn "  listRepositories returned HTTP $code — configured anyway ($hint)"
      ;;
  esac
  return 0
}

run_probes() {
  local i
  echo ""
  info "MCP connection checks (informational only):"
  for i in "${ENV_SELECTED_INDICES[@]}"; do
    printf "  %-16s %s\n" "${ENV_NAMES[$i]}" "${ENV_BASE_URLS[$i]}"
    probe_mcp "${ENV_NAMES[$i]}" "${ENV_BASE_URLS[$i]}" "${ENV_TOKENS[$i]}"
  done
  echo ""
}

# Build the server object as JSON.
server_object() {
  local mcp_url="$1" with_token="$2" token_value="$3"
  if [[ "$with_token" == "true" ]]; then
    printf '{"url":"%s","headers":{"Authorization":"Bearer %s"}}' "$mcp_url" "$token_value"
  else
    printf '{"url":"%s"}' "$mcp_url"
  fi
}

merge_mcp_server() {
  local file="$1" server_name="$2" mcp_url="$3" with_token="$4" token_value="$5"
  local dir obj
  dir="$(dirname "$file")"
  mkdir -p "$dir"
  obj="$(server_object "$mcp_url" "$with_token" "$token_value")"

  if [[ -f "$file" ]]; then
    if [[ ! -f "${file}.backup" ]]; then
      cp "$file" "$file.backup"
      info "Backup: $file.backup"
    fi
    if have_jq; then
      local clean
      clean="$(cat "$file")"
      [[ -z "$(printf '%s' "$clean" | tr -d '[:space:]')" ]] && clean='{}'
      if printf '%s' "$clean" | jq --arg name "$server_name" --argjson obj "$obj" \
          '.mcpServers = (.mcpServers // {}) | .mcpServers[$name] = $obj' > "$file.tmp" 2>/dev/null; then
        mv "$file.tmp" "$file"
      else
        rm -f "$file.tmp"
        err "Could not merge $file (invalid JSON?). Backup preserved at $file.backup"
        return 1
      fi
    else
      warn "jq not found — cannot merge $server_name into $file safely."
      return 1
    fi
  else
    cat > "$file" <<EOF
{
  "mcpServers": {
    "$server_name": $obj
  }
}
EOF
  fi
  chmod 644 "$file"
}

write_all_mcp_servers() {
  local file="$1" use_env_placeholders="$2"
  local i name mcp_url token with_token token_value project_token_var count=0

  for i in "${ENV_SELECTED_INDICES[@]}"; do
    name="${ENV_NAMES[$i]}"
    mcp_url="${ENV_MCP_URLS[$i]}"
    token="${ENV_TOKENS[$i]}"
    with_token=false
    token_value=""

    if [[ -n "$token" ]]; then
      with_token=true
      if [[ "$use_env_placeholders" == "true" ]]; then
        project_token_var="${ENV_PROJECT_TOKEN_VARS[$i]}"
        token_value="\${env:${project_token_var}}"
      else
        token_value="$token"
      fi
    fi

    merge_mcp_server "$file" "$name" "$mcp_url" "$with_token" "$token_value"
    count=$((count + 1))
  done

  if [[ -f "$file" ]]; then
    ok "Updated $file ($count Archie environment(s))"
  else
    ok "Created $file ($count Archie environment(s))"
  fi
}

print_token_reminders() {
  local i name token missing=()
  for i in "${ENV_SELECTED_INDICES[@]}"; do
    name="${ENV_NAMES[$i]}"
    token="${ENV_TOKENS[$i]}"
    [[ -n "$token" ]] && continue
    missing+=("$name")
  done
  [[ ${#missing[@]} -eq 0 ]] && return 0

  echo ""
  warn "Bearer tokens still needed for: ${missing[*]}"
  if [[ -n "$PROJECT_DIR" ]]; then
    echo "  Project install uses env placeholders — export before launching Cursor:"
    for i in "${ENV_SELECTED_INDICES[@]}"; do
      [[ -n "${ENV_TOKENS[$i]}" ]] && continue
      echo "    export ${ENV_PROJECT_TOKEN_VARS[$i]}=\"<bearer>\""
    done
    echo "  Launch Cursor from a terminal where those vars are set, or add them in Cursor env settings."
  else
    echo "  Re-run the installer (or curl -fsSL <install-url> | bash) and paste tokens, or edit ~/.cursor/mcp.json."
    echo "  Token locations:"
    for i in "${ENV_SELECTED_INDICES[@]}"; do
      [[ -n "${ENV_TOKENS[$i]}" ]] && continue
      echo "    ${ENV_NAMES[$i]}: $(token_hint "${ENV_NAMES[$i]}")"
    done
  fi
}

selected_env_names() {
  local i names=()
  (( ${#ENV_SELECTED_INDICES[@]} )) || return 0
  for i in "${ENV_SELECTED_INDICES[@]}"; do
    names+=("${ENV_NAMES[$i]}")
  done
  (IFS=', '; echo "${names[*]}")
}

# --- main install flow -------------------------------------------------------
detect_script_mode
select_environments
collect_tokens
run_probes

USER_MCP="$HOME/.cursor/mcp.json"
write_all_mcp_servers "$USER_MCP" false

if [[ "$INSTALL_SKILLS" == "true" ]]; then
  install_skills
fi

if [[ -n "$PROJECT_DIR" ]]; then
  if [[ ! -d "$PROJECT_DIR" ]]; then
    err "Project dir not found: $PROJECT_DIR"; exit 2
  fi
  PROJECT_DIR="$(cd "$PROJECT_DIR" && pwd)"
  PROJECT_MCP="$PROJECT_DIR/.cursor/mcp.json"
  write_all_mcp_servers "$PROJECT_MCP" true
  RULES_DIR="$PROJECT_DIR/.cursor/rules"
  install_guideline_rule "$RULES_DIR/archie.mdc"
fi

echo ""
echo "${GREEN}============================================${NC}"
echo "${GREEN}  Archie + Cursor: setup complete${NC}"
echo "${GREEN}============================================${NC}"
echo ""
print_token_reminders
echo ""
info "Next steps:"
echo "  1. Fully restart Cursor (or toggle servers in Settings -> MCP)."
echo "  2. Settings -> MCP should list: $(selected_env_names)."
echo "  3. Enable the environment you want and try: 'Using archie, list the available repositories.'"
echo ""
info "Toggle environments in Cursor Settings -> MCP. Local MCP is :8081 (API dashboard is :8080)."
info "If a server shows red in MCP settings, check MCP Logs (Ctrl+Shift+U) for auth errors."
