#!/usr/bin/env bash
# Mnemo Cortex — Claude Code Integration Installer
# Gives Claude Code persistent memory that survives across sessions.
# https://github.com/GuyMannDude/mnemo-cortex
set -euo pipefail

INSTALL_DIR="${HOME}/.mnemo-cc"
HOOKS_DIR="${INSTALL_DIR}/hooks"

# ─────────────────────────────────────────────
# Colors
# ─────────────────────────────────────────────
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
BOLD='\033[1m'
NC='\033[0m'

info()  { echo -e "${BLUE}▸${NC} $1"; }
ok()    { echo -e "${GREEN}✓${NC} $1"; }
warn()  { echo -e "${YELLOW}!${NC} $1"; }
fail()  { echo -e "${RED}✗${NC} $1"; exit 1; }

# ─────────────────────────────────────────────
# Header
# ─────────────────────────────────────────────
echo ""
echo -e "${BOLD}Mnemo Cortex — Claude Code Integration${NC}"
echo "Persistent memory for Claude Code. Total recall across sessions."
echo ""

# ─────────────────────────────────────────────
# Prerequisites
# ─────────────────────────────────────────────
command -v curl >/dev/null 2>&1 || fail "curl is required but not installed"
command -v python3 >/dev/null 2>&1 || fail "python3 is required but not installed"

# ─────────────────────────────────────────────
# Step 1: Mnemo Cortex URL
# ─────────────────────────────────────────────
echo -e "${BOLD}Step 1: Where is Mnemo Cortex running?${NC}"
echo ""
echo "  If it's on this machine:  http://localhost:50001  (default)"
echo "  If it's on another machine: http://hostname:50001"
echo ""
read -rp "Mnemo Cortex URL [http://localhost:50001]: " MNEMO_URL
MNEMO_URL="${MNEMO_URL:-http://localhost:50001}"
# Strip trailing slash
MNEMO_URL="${MNEMO_URL%/}"

info "Testing connection to ${MNEMO_URL}..."
if health=$(curl -sf --max-time 5 "${MNEMO_URL}/health" 2>/dev/null); then
    status=$(echo "$health" | python3 -c "import sys,json; print(json.load(sys.stdin).get('status','unknown'))" 2>/dev/null || echo "unknown")
    ok "Connected! Status: ${status}"
else
    warn "Could not reach ${MNEMO_URL}"
    echo ""
    echo "  Make sure mnemo-cortex is running. To start it:"
    echo "    cd /path/to/mnemo-cortex && python -m uvicorn agentb.server:app --port 50001"
    echo ""
    read -rp "Continue anyway? (y/N): " cont
    [[ "$cont" =~ ^[Yy] ]] || exit 1
fi
echo ""

# ─────────────────────────────────────────────
# Step 2: Agent ID
# ─────────────────────────────────────────────
echo -e "${BOLD}Step 2: Choose your agent ID${NC}"
echo ""
echo "  This identifies your Claude Code sessions in Mnemo Cortex."
echo "  If you're the only user, 'cc' is fine."
echo "  If multiple people share a server, use something unique (e.g., your name)."
echo ""
read -rp "Agent ID [cc]: " AGENT_ID
AGENT_ID="${AGENT_ID:-cc}"
echo ""

# ─────────────────────────────────────────────
# Step 3: Install hooks
# ─────────────────────────────────────────────
echo -e "${BOLD}Step 3: Installing...${NC}"
echo ""

mkdir -p "$HOOKS_DIR" "${INSTALL_DIR}/queue"

# Determine source directory (works whether run from repo or via curl)
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

if [ -f "${SCRIPT_DIR}/mnemo-startup.sh" ]; then
    cp "${SCRIPT_DIR}/mnemo-startup.sh" "${HOOKS_DIR}/mnemo-startup.sh"
    cp "${SCRIPT_DIR}/mnemo-writeback.sh" "${HOOKS_DIR}/mnemo-writeback.sh"
else
    # Downloading from GitHub
    info "Downloading hook scripts..."
    curl -sf "https://raw.githubusercontent.com/GuyMannDude/mnemo-cortex/master/integrations/claude-code/mnemo-startup.sh" \
        -o "${HOOKS_DIR}/mnemo-startup.sh" || fail "Failed to download mnemo-startup.sh"
    curl -sf "https://raw.githubusercontent.com/GuyMannDude/mnemo-cortex/master/integrations/claude-code/mnemo-writeback.sh" \
        -o "${HOOKS_DIR}/mnemo-writeback.sh" || fail "Failed to download mnemo-writeback.sh"
fi

chmod +x "${HOOKS_DIR}/mnemo-startup.sh" "${HOOKS_DIR}/mnemo-writeback.sh"
ok "Hook scripts installed to ${HOOKS_DIR}/"

# Write env config
cat > "${INSTALL_DIR}/env" <<EOF
# Mnemo Cortex — Claude Code config
# Generated by install.sh on $(date -Iseconds)
MNEMO_URL="${MNEMO_URL}"
MNEMO_AGENT_ID="${AGENT_ID}"
EOF
ok "Config saved to ${INSTALL_DIR}/env"

# ─────────────────────────────────────────────
# Step 4: Update CLAUDE.md
# ─────────────────────────────────────────────
echo ""
echo -e "${BOLD}Step 4: Wiring into Claude Code${NC}"
echo ""

STARTUP_BLOCK='## MNEMO CORTEX — PERSISTENT MEMORY
On every new session, run: `~/.mnemo-cc/hooks/mnemo-startup.sh`
Before ending any session, run: `~/.mnemo-cc/hooks/mnemo-writeback.sh "summary of session" "key fact 1" "key fact 2"`'

# Find CLAUDE.md — check project dir first, then home
CLAUDE_MD=""
if [ -f "./CLAUDE.md" ]; then
    CLAUDE_MD="./CLAUDE.md"
elif [ -f "${HOME}/CLAUDE.md" ]; then
    CLAUDE_MD="${HOME}/CLAUDE.md"
fi

if [ -n "$CLAUDE_MD" ]; then
    # Check if already installed
    if grep -q "mnemo-startup.sh" "$CLAUDE_MD" 2>/dev/null; then
        ok "CLAUDE.md already has mnemo hooks (${CLAUDE_MD})"
    else
        echo ""
        echo "  Found: ${CLAUDE_MD}"
        echo "  I'll add the startup/writeback instructions to it."
        echo ""
        read -rp "  Add mnemo hooks to ${CLAUDE_MD}? (Y/n): " add_hooks
        if [[ ! "$add_hooks" =~ ^[Nn] ]]; then
            echo "" >> "$CLAUDE_MD"
            echo "$STARTUP_BLOCK" >> "$CLAUDE_MD"
            ok "Added mnemo hooks to ${CLAUDE_MD}"
        else
            warn "Skipped. You'll need to add the hooks manually."
            echo "  See: ${INSTALL_DIR}/../CLAUDE.md.example"
        fi
    fi
else
    echo "  No CLAUDE.md found. Creating one at ~/CLAUDE.md"
    read -rp "  Create ~/CLAUDE.md with mnemo hooks? (Y/n): " create_claude
    if [[ ! "$create_claude" =~ ^[Nn] ]]; then
        echo "$STARTUP_BLOCK" > "${HOME}/CLAUDE.md"
        ok "Created ${HOME}/CLAUDE.md"
        CLAUDE_MD="${HOME}/CLAUDE.md"
    else
        warn "Skipped. See CLAUDE.md.example for what to add manually."
    fi
fi

# ─────────────────────────────────────────────
# Step 5: Test
# ─────────────────────────────────────────────
echo ""
echo -e "${BOLD}Step 5: Testing...${NC}"
echo ""

# Test startup
info "Running mnemo-startup.sh..."
if output=$("${HOOKS_DIR}/mnemo-startup.sh" 2>&1); then
    lines=$(echo "$output" | wc -l)
    ok "Startup hook works (${lines} lines of context loaded)"
else
    warn "Startup hook returned an error (this is OK if the server is not running yet)"
fi

# Test writeback
info "Running test writeback..."
if output=$("${HOOKS_DIR}/mnemo-writeback.sh" "Mnemo Cortex Claude Code integration installed" "agent_id: ${AGENT_ID}" 2>&1); then
    ok "Writeback works: ${output}"
else
    warn "Writeback failed (this is OK if the server is not running yet)"
fi

# ─────────────────────────────────────────────
# Done
# ─────────────────────────────────────────────
echo ""
echo -e "${GREEN}${BOLD}Done!${NC} Mnemo Cortex is wired into Claude Code."
echo ""
echo "  Hooks:   ${HOOKS_DIR}/"
echo "  Config:  ${INSTALL_DIR}/env"
if [ -n "$CLAUDE_MD" ]; then
echo "  CLAUDE.md: ${CLAUDE_MD}"
fi
echo ""
echo "  Next time you start Claude Code, it will load your memory automatically."
echo "  When you end a session, tell CC to run the writeback hook."
echo ""
echo "  To uninstall: rm -rf ${INSTALL_DIR}"
if [ -n "$CLAUDE_MD" ]; then
echo "                 Remove the MNEMO CORTEX block from ${CLAUDE_MD}"
fi
echo ""
