#!/usr/bin/env bash
# TWC executive setup for Claude Code.
# Wires up, in one run: (1) Fable mode, (2) the ADP connector, (3) the Domo
# connector. Each section is optional. It is idempotent and verifies as it goes.
# Nothing sensitive is stored in this file; you paste your own keys when asked.
#
# Run it:  bash ~/Downloads/adp-setup.sh
set -euo pipefail

ADP_URL="https://crdvhc3mmp.us-east-2.awsapprunner.com/mcp"
DOMO_INSTANCE="thewiredconnection.domo.com"
PROFILE="${HOME}/.zshrc"
FABLE_MARKER="# >>> twc claude-fable >>>"

bold(){ printf "\033[1m%s\033[0m\n" "$1"; }
ok(){ printf "  \033[32m✓\033[0m %s\n" "$1"; }
warn(){ printf "  \033[33m!\033[0m %s\n" "$1"; }
ask(){ # ask "prompt" -> echoes answer (reads real tty even under pipe)
  local a=""; if [ -r /dev/tty ]; then printf "%s" "$1" > /dev/tty; read -r a < /dev/tty || a=""; fi
  printf '%s' "$a" | tr -d '[:space:]'
}

echo; bold "TWC · Claude Code executive setup"
echo "You'll be asked for up to three keys. Press Return to skip any section."
echo

# ---- prerequisite: Claude Code ---------------------------------------------
if ! command -v claude >/dev/null 2>&1; then
  warn "Claude Code isn't installed yet."
  echo "     Set it up first (2 min): https://faster.newpiedpiper.net/claude-code"
  echo "     Then run this again."
  exit 1
fi
ok "Claude Code found ($(claude --version 2>/dev/null | head -1))"

SETUP=()  # track what we actually wired, so the summary needs no health check

# ---- 1. Fable mode ---------------------------------------------------------
echo; bold "1) Fable mode"
echo "   Adds a 'claude-fable' command that runs Claude on the non-PHI key with"
echo "   Fable 5 turned on. Your normal 'claude' command is left untouched."
echo "   Note: Fable needs you signed OUT of the TWC enterprise Claude account"
echo "   first (it's zero-retention and blocks Fable). You'll run 'claude logout'"
echo "   before launching. Full steps print after this installs."
FKEY="$(ask '   Paste your Fable (non-PHI) API key, or Return to skip: ')"
if [ -n "$FKEY" ]; then
  if grep -qF "$FABLE_MARKER" "$PROFILE" 2>/dev/null; then
    # Replace the existing block so re-runs update the key rather than stack.
    tmp="$(mktemp)"; awk -v m="$FABLE_MARKER" '
      $0==m{skip=1} skip&&/# <<< twc claude-fable <<</{skip=0;next} !skip' "$PROFILE" > "$tmp" && mv "$tmp" "$PROFILE"
  fi
  {
    echo "$FABLE_MARKER"
    echo "claude-fable() { ANTHROPIC_API_KEY=\"$FKEY\" ANTHROPIC_MODEL=\"claude-fable-5\" claude \"\$@\"; }"
    echo "# <<< twc claude-fable <<<"
  } >> "$PROFILE"
  ok "Fable mode installed."
  warn "Before it works, sign out of your enterprise Claude account."
  echo "     Your TWC enterprise account is HIPAA (zero data retention), and"
  echo "     Fable requires retention on. While you're signed in to it, Claude Code"
  echo "     uses that account and refuses Fable with a 'data retention' error, even"
  echo "     with your Fable key set. So the first time, and any time you've logged"
  echo "     back in to the enterprise account:"
  echo "        claude logout      # sign out of the enterprise account"
  echo "        claude-fable       # now runs on your Fable key"
  echo "     Use '/login' inside Claude when you want the normal enterprise 'claude'"
  echo "     back (you'll 'claude logout' again next time you want Fable)."
  SETUP+=("Fable mode  (run 'claude logout' first, then: claude-fable)")
else
  warn "Skipped Fable mode."
fi

# ---- 2. ADP (read-only) ----------------------------------------------------
echo; bold "2) ADP (read-only)"
echo "   Live headcount, org breakdowns, pay-grade bands, payroll runs."
AKEY="$(ask '   Paste your ADP access key, or Return to skip: ')"
if [ -n "$AKEY" ]; then
  claude mcp remove adp -s user >/dev/null 2>&1 || true
  claude mcp add --transport http adp "$ADP_URL" \
    --header "Authorization: Bearer $AKEY" --scope user >/dev/null
  ok "ADP connected."
  SETUP+=("ADP  (read-only: headcount, org, pay bands, payroll)")
else
  warn "Skipped ADP."
fi

# ---- 3. Domo ---------------------------------------------------------------
echo; bold "3) Domo"
echo "   Query datasets, cards, and dashboards on ${DOMO_INSTANCE}."
DKEY="$(ask '   Paste your Domo access token, or Return to skip: ')"
if [ -n "$DKEY" ]; then
  if ! command -v npm >/dev/null 2>&1; then
    warn "Domo needs Node.js (for npm), which isn't installed."
    echo "     Install it with:  brew install node    then run this again."
  else
    # The Domo MCP server (github.com/BFullenkampDomo/CommunityDomoMCPHelix,
    # MIT) is not published on npm, so we never install it by bare package
    # name -- an unclaimed npm name is a squatting target. We fetch this
    # exact reviewed commit from GitHub, build it locally, and point Claude
    # at the built file, so nothing is fetched from a registry at launch.
    HELIX_COMMIT="9fc6e5e272717473a7a965356e9aa6ce6493ed67"
    HELIX_DIR="${HOME}/.twc/domo-mcp"
    echo "   Installing the Domo connector (pinned build, ~30s)..."
    rm -rf "$HELIX_DIR"; mkdir -p "$HELIX_DIR"
    if curl -fsSL "https://codeload.github.com/BFullenkampDomo/CommunityDomoMCPHelix/tar.gz/${HELIX_COMMIT}" \
        | tar -xz --strip-components=1 -C "$HELIX_DIR" \
      && (cd "$HELIX_DIR" && npm install --no-audit --no-fund >/dev/null 2>&1 \
          && npm run build >/dev/null 2>&1); then
      claude mcp remove domo -s user >/dev/null 2>&1 || true
      claude mcp add --transport stdio domo -s user \
        -e "DOMO_INSTANCE=${DOMO_INSTANCE}" -e "DOMO_TOKEN=${DKEY}" \
        -- node "${HELIX_DIR}/dist/index.js" >/dev/null
      ok "Domo connected."
      SETUP+=("Domo  (datasets, cards, dashboards)")
    else
      warn "Couldn't download or build the Domo connector, so it was skipped."
      echo "     Check your network and re-run this script. Everything else still applied."
    fi
  fi
else
  warn "Skipped Domo."
fi

# ---- summary ---------------------------------------------------------------
# We report what we just wired rather than running `claude mcp list`, which
# health-checks EVERY server already configured and can crawl or hang on an
# unrelated one. Check everything yourself anytime with:  claude mcp list
echo; bold "Set up this run"
if [ ${#SETUP[@]} -eq 0 ]; then
  warn "Nothing selected (you skipped every section). Re-run and paste a key to connect one."
else
  for s in "${SETUP[@]}"; do ok "$s"; done
fi
echo "  See all your connections anytime with:  claude mcp list"

echo; bold "Done. Restart Claude Code, then ask things like:"
cat <<'ASK'
   • How many active employees do we have? Break it down by business unit.
   • What were the last few payroll runs?
   • What's the pay-grade band for a Clinical team lead?
   • (Domo) What datasets do we have on revenue? Show me the latest card values.
ASK
echo "If you set up Fable: run 'claude logout' first (the enterprise account is"
echo "zero-retention and blocks Fable), then launch with 'claude-fable'. Everything"
echo "is read-only for ADP. To remove a connector later: claude mcp remove <name> -s user"
echo
