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

# compounding-memory skill installer.
# CONTEXT-locked: one URL → bootstrap (skill + MCP server + OAuth + sanity probe).
#
# Usage:
#   curl -fsSL https://skill.compoundingmemory.com/skill/install.sh | bash
#   curl -fsSL https://skill.compoundingmemory.com/skill/install.sh | bash -s -- --org=acme
#   ./install.sh --dry-run
#   ./install.sh --force
#
# Flags:
#   --org=<id>   Org id for the MCP server URL. Prompts if absent.
#   --dry-run    Print steps and exit 0; no filesystem changes.
#   --force      Overwrite existing ~/.claude/skills/compounding-memory.
#   --help|-h    Show this help.
#
# Env:
#   INSTALL_PREFIX     Root for ~/.claude (defaults to $HOME). Used by tests.
#   CLAUDE_MCP_DRYRUN  If set, skip `claude mcp add` (test-only).
#   CM_MCP_TOKEN_ENV   If set, prefer .env over keychain (per CONTEXT decision).

DRY_RUN=0
FORCE=0
ORG_ID=""

for arg in "$@"; do
  case "$arg" in
    --dry-run) DRY_RUN=1 ;;
    --force)   FORCE=1 ;;
    --org=*)   ORG_ID="${arg#*=}" ;;
    -h|--help) sed -n '4,21p' "$0"; exit 0 ;;
    *) echo "unknown arg: $arg" >&2; exit 2 ;;
  esac
done

PREFIX="${INSTALL_PREFIX:-$HOME}"
SKILL_DIR="${PREFIX}/.claude/skills/compounding-memory"

say() { echo "[install] $*"; }

step_1_detect_platform() {
  say "step 1/5: detecting platform"
  case "$(uname -s)" in
    Darwin) PLATFORM=macos ;;
    Linux)  PLATFORM=linux ;;
    *)      PLATFORM=other ;;
  esac
  say "  platform=${PLATFORM}"
}

step_2_copy_skill() {
  say "step 2/5: copying skill bundle to ${SKILL_DIR}"
  if [ "$DRY_RUN" -eq 1 ]; then
    say "  (dry-run, skipping)"
    return
  fi
  if [ -d "$SKILL_DIR" ] && [ "$FORCE" -ne 1 ]; then
    say "  ${SKILL_DIR} exists; pass --force to overwrite"
    exit 1
  fi
  mkdir -p "${SKILL_DIR}/references" "${SKILL_DIR}/scripts/api-client"
  # During in-repo test runs, copy from $(dirname "$0")/../.. (the bundle root).
  # When invoked via curl | bash, fetch from a hosted bundle URL — but that's
  # plan 10-16 terraform's job; for this plan, the in-repo path is what we test.
  local SRC_ROOT
  SRC_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
  cp "${SRC_ROOT}/SKILL.md"                 "${SKILL_DIR}/SKILL.md"
  cp "${SRC_ROOT}/README.md"                "${SKILL_DIR}/README.md"
  cp "${SRC_ROOT}/references/error-codes.md" "${SKILL_DIR}/references/error-codes.md"
  cp "${SRC_ROOT}/scripts/api-client/openapi-ts.config.ts" "${SKILL_DIR}/scripts/api-client/openapi-ts.config.ts"
}

step_3_register_mcp() {
  say "step 3/5: registering MCP server"
  if [ -z "${ORG_ID:-}" ]; then
    read -rp "Org id (e.g. acme): " ORG_ID
  fi
  local URL="https://mcp.compoundingmemory.com/${ORG_ID}/mcp"
  say "  url=${URL}"
  if [ "$DRY_RUN" -eq 1 ] || [ -n "${CLAUDE_MCP_DRYRUN:-}" ]; then
    say "  (skipping claude mcp add)"
    return
  fi
  if ! command -v claude >/dev/null; then
    say "  claude CLI not found; install Claude Code first"
    exit 1
  fi
  claude mcp add --transport http compounding-memory "${URL}"
}

step_4_codegen() {
  say "step 4/5: install-time TS codegen via @hey-api/openapi-ts"
  if [ "$DRY_RUN" -eq 1 ]; then
    say "  (dry-run, skipping)"
    return
  fi
  ( cd "${SKILL_DIR}/scripts/api-client" && npx -y @hey-api/openapi-ts@^0.96 ) || \
    say "  codegen failed; skill still works (skill scripts call the MCP server, not the API client directly — codegen is a forward-compat helper)"
}

step_5_probe() {
  say "step 5/5: post-install guidance"
  cat <<EOF
Next steps:
  1. Open Claude Code.
  2. Run /mcp to authenticate via WorkOS (browser will open).
  3. Try: "what did we decide about pricing?"
     The agent will call search_memory and cite source URLs.

Token storage: ${CM_MCP_TOKEN_ENV:+env-var (CM_MCP_TOKEN_ENV=1 set)}${CM_MCP_TOKEN_ENV:-keychain (default)}
Override: see scripts/store-token.sh.
EOF
}

step_1_detect_platform
step_2_copy_skill
step_3_register_mcp
step_4_codegen
step_5_probe

exit 0
