#!/usr/bin/env bash
# Locamem installer — local-first memory for AI agents. Runs entirely on your box.
#
#   curl -fsSL https://locamem.com/install | bash
#
# Installs the engine, then auto-detects MCP clients (Claude Code, Claude Desktop,
# Codex) and wires Locamem in over stdio — backing up any config it touches.
# Nothing leaves your machine: the store is a single local SQLite file.
set -euo pipefail

REPO="${LOCAMEM_REPO:-git+https://github.com/TeamWilcoe/ha5h.git}"
MODULE="ha5h.mcp.server"          # internal module (package rename pending)
NAME="locamem"
STORE="${LOCAMEM_HOME:-$HOME/.locamem}"
BLUE='\033[1;35m'; GRN='\033[1;32m'; DIM='\033[2m'; RED='\033[1;31m'; NC='\033[0m'

say()  { printf "${BLUE}◆${NC} %s\n" "$*"; }
ok()   { printf "${GRN}✓${NC} %s\n" "$*"; }
warn() { printf "${RED}!${NC} %s\n" "$*"; }

say "Locamem — local-first agent memory (no cloud, no egress)"

# 1) Python + pip ------------------------------------------------------------
PY="$(command -v python3 || command -v python || true)"
[ -z "$PY" ] && { warn "Python 3.10+ required and not found."; exit 1; }
say "Using $($PY --version 2>&1) at $PY"

# 2) Install the engine ------------------------------------------------------
say "Installing the engine (pip install '${NAME}[mcp]')…"
if "$PY" -m pip install --user --upgrade "ha5h[mcp] @ ${REPO}" >/tmp/locamem_pip.log 2>&1; then
  ok "Engine installed."
else
  warn "pip install failed — see /tmp/locamem_pip.log"; tail -5 /tmp/locamem_pip.log; exit 1
fi

mkdir -p "$STORE"
ok "Local store ready at $STORE (single SQLite file; never leaves this machine)."

STDIO_CMD="$PY -m ${MODULE} --crystal ${STORE}"

backup() { [ -f "$1" ] && cp "$1" "$1.locamem-bak.$(date +%s)" && say "Backed up $1"; }

WIRED=0

# 3a) Claude Code (CLI) ------------------------------------------------------
if command -v claude >/dev/null 2>&1; then
  say "Detected Claude Code — registering MCP server…"
  if claude mcp add "$NAME" -- $STDIO_CMD >/dev/null 2>&1; then
    ok "Claude Code: '$NAME' registered (stdio). Restart Claude Code to load it."
    WIRED=1
  else
    warn "claude mcp add failed; add manually:  claude mcp add $NAME -- $STDIO_CMD"
  fi
fi

# 3b) Claude Desktop (config JSON) ------------------------------------------
case "$(uname -s)" in
  Darwin) CD_CFG="$HOME/Library/Application Support/Claude/claude_desktop_config.json" ;;
  Linux)  CD_CFG="$HOME/.config/Claude/claude_desktop_config.json" ;;
  *)      CD_CFG="" ;;
esac
if [ -n "$CD_CFG" ] && [ -d "$(dirname "$CD_CFG")" ]; then
  say "Detected Claude Desktop — updating $CD_CFG…"
  backup "$CD_CFG"
  [ -f "$CD_CFG" ] || echo '{}' > "$CD_CFG"
  "$PY" - "$CD_CFG" "$NAME" "$PY" "$MODULE" "$STORE" <<'PYEOF'
import json, sys
cfg_path, name, py, module, store = sys.argv[1:6]
try:
    cfg = json.load(open(cfg_path))
except Exception:
    cfg = {}
cfg.setdefault("mcpServers", {})[name] = {
    "command": py, "args": ["-m", module, "--crystal", store],
}
json.dump(cfg, open(cfg_path, "w"), indent=2)
print("  wrote mcpServers.%s" % name)
PYEOF
  ok "Claude Desktop: '$NAME' added. Restart Claude Desktop to load it."
  WIRED=1
fi

# 3c) Codex (best-effort note) ----------------------------------------------
if command -v codex >/dev/null 2>&1; then
  say "Detected Codex — add an MCP server pointing at the HTTP transport:"
  printf "${DIM}    %s -m %s --transport http --port 3100   # then point Codex at http://127.0.0.1:3100/mcp${NC}\n" "$PY" "$MODULE"
fi

echo
if [ "$WIRED" = "1" ]; then
  ok "Locamem is wired in. Try asking your agent to 'remember' something, then recall it."
else
  warn "No supported client auto-detected. Manual setup:"
  echo "    Claude Code:    claude mcp add $NAME -- $STDIO_CMD"
  echo "    HTTP clients:   $PY -m $MODULE --transport http --port 3100   ->  http://127.0.0.1:3100/mcp"
fi
echo
say "Docs: https://docs.locamem.com   ·   Store: $STORE   ·   100% local."
