#!/bin/bash
#
# Nexus Memory - Installation Script
# Installs the Nexus Memory skill for Claude Code with automatic memory features.
#
# Usage:
#   curl -fsSL https://raw.githubusercontent.com/adverant/nexus-memory-skill/main/install.sh | bash
#   OR
#   ./install.sh
#
# What this script does:
# 1. Creates necessary directories (~/.claude/skills, ~/.claude/hooks)
# 2. Copies skill and hook files
# 3. Configures settings.json for automatic memory
# 4. Helps you set up your API key (opens browser if needed)
# 5. Verifies the installation
#

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Logging functions
log_info() {
  echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
  echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warn() {
  echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
  echo -e "${RED}[ERROR]${NC} $1"
}

# Check for required commands
check_dependencies() {
  local missing=()

  if ! command -v curl &> /dev/null; then
    missing+=("curl")
  fi

  if ! command -v jq &> /dev/null; then
    missing+=("jq")
  fi

  if [ ${#missing[@]} -ne 0 ]; then
    log_error "Missing required dependencies: ${missing[*]}"
    echo ""
    echo "Please install them first:"
    if [[ "$OSTYPE" == "darwin"* ]]; then
      echo "  brew install ${missing[*]}"
    else
      echo "  sudo apt-get install ${missing[*]}"
    fi
    exit 1
  fi
}

# Get the script directory (works for both local and remote install)
get_source_dir() {
  if [ -d "$(dirname "$0")/hooks" ]; then
    echo "$(cd "$(dirname "$0")" && pwd)"
  else
    # Remote install - download to temp directory
    local temp_dir=$(mktemp -d)
    log_info "Downloading Nexus Memory skill..."
    git clone --depth 1 https://github.com/adverant/nexus-memory-skill.git "$temp_dir" 2>/dev/null || {
      log_error "Failed to download. Please check your internet connection."
      exit 1
    }
    echo "$temp_dir"
  fi
}

# Create required directories
create_directories() {
  log_info "Creating directories..."
  mkdir -p ~/.claude/skills/nexus-memory
  mkdir -p ~/.claude/hooks
  mkdir -p ~/.claude/session-env
}

# Copy skill and hooks
install_files() {
  local source_dir="$1"

  log_info "Installing skill file..."
  cp "$source_dir/SKILL.md" ~/.claude/skills/nexus-memory/SKILL.md

  log_info "Installing hooks..."
  cp "$source_dir/hooks/store-memory.sh" ~/.claude/hooks/
  cp "$source_dir/hooks/recall-memory.sh" ~/.claude/hooks/
  cp "$source_dir/hooks/auto-recall.sh" ~/.claude/hooks/
  cp "$source_dir/hooks/episode-summary.sh" ~/.claude/hooks/

  # Make hooks executable
  chmod +x ~/.claude/hooks/store-memory.sh
  chmod +x ~/.claude/hooks/recall-memory.sh
  chmod +x ~/.claude/hooks/auto-recall.sh
  chmod +x ~/.claude/hooks/episode-summary.sh

  # Copy upload-document.sh if it exists
  if [ -f "$source_dir/hooks/upload-document.sh" ]; then
    cp "$source_dir/hooks/upload-document.sh" ~/.claude/hooks/
    chmod +x ~/.claude/hooks/upload-document.sh
  fi

  # Copy auto-ingest hooks (v2.4.0+)
  if [ -f "$source_dir/hooks/auto-ingest.sh" ]; then
    cp "$source_dir/hooks/auto-ingest.sh" ~/.claude/hooks/
    chmod +x ~/.claude/hooks/auto-ingest.sh
  fi

  if [ -f "$source_dir/hooks/ingest-notify.sh" ]; then
    cp "$source_dir/hooks/ingest-notify.sh" ~/.claude/hooks/
    chmod +x ~/.claude/hooks/ingest-notify.sh
  fi

  # Copy API key helper if it exists
  if [ -f "$source_dir/hooks/api-key-helper.sh" ]; then
    cp "$source_dir/hooks/api-key-helper.sh" ~/.claude/hooks/
    chmod +x ~/.claude/hooks/api-key-helper.sh
  fi

  # Copy bead-sync hook if it exists
  if [ -f "$source_dir/hooks/bead-sync.sh" ]; then
    cp "$source_dir/hooks/bead-sync.sh" ~/.claude/hooks/
    chmod +x ~/.claude/hooks/bead-sync.sh
  fi

  log_success "Files installed successfully"
}

# Configure settings.json
configure_settings() {
  log_info "Configuring Claude Code settings..."

  local settings_file=~/.claude/settings.json

  # Create settings.json with automatic memory hooks (including auto-ingest)
  cat > "$settings_file" << 'EOF'
{
  "hooks": {
    "UserPromptSubmit": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": "~/.claude/hooks/auto-recall.sh"
          },
          {
            "type": "command",
            "command": "~/.claude/hooks/auto-ingest.sh"
          },
          {
            "type": "command",
            "command": "~/.claude/hooks/store-memory.sh"
          }
        ]
      }
    ],
    "PostToolUse": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": "~/.claude/hooks/auto-ingest.sh"
          },
          {
            "type": "command",
            "command": "~/.claude/hooks/store-memory.sh"
          },
          {
            "type": "command",
            "command": "~/.claude/hooks/episode-summary.sh"
          }
        ]
      }
    ]
  }
}
EOF

  log_success "Settings configured for automatic memory"
}

# Open browser to get API key
open_browser() {
  local url="$1"

  if [[ "$OSTYPE" == "darwin"* ]]; then
    open "$url" 2>/dev/null || true
  elif [[ "$OSTYPE" == "linux-gnu"* ]]; then
    xdg-open "$url" 2>/dev/null || true
  elif [[ "$OSTYPE" == "msys" ]] || [[ "$OSTYPE" == "cygwin" ]]; then
    start "$url" 2>/dev/null || true
  fi
}

# Setup API key
setup_api_key() {
  echo ""
  log_info "Checking API key configuration..."

  if [ -n "$NEXUS_API_KEY" ]; then
    log_success "NEXUS_API_KEY is already configured"
    return 0
  fi

  echo ""
  echo -e "${YELLOW}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
  echo -e "${YELLOW}                    API Key Setup Required                               ${NC}"
  echo -e "${YELLOW}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
  echo ""
  echo "Nexus Memory requires an API key to store and recall memories."
  echo ""
  echo "Steps to get your API key:"
  echo "  1. A browser window will open to the Nexus Dashboard"
  echo "  2. Log in or create a free account"
  echo "  3. Navigate to 'API Keys' section"
  echo "  4. Click 'Create New Key'"
  echo "  5. Copy your new API key"
  echo ""

  read -p "Press Enter to open the dashboard in your browser..."

  open_browser "https://dashboard.adverant.ai/dashboard/api-keys"

  echo ""
  echo "Paste your API key below (it will be hidden):"
  read -s api_key
  echo ""

  if [ -z "$api_key" ]; then
    log_warn "No API key provided. You can set it later with:"
    echo "  export NEXUS_API_KEY='your-api-key-here'"
    return 1
  fi

  # Detect shell profile
  local shell_profile=""
  if [ -f ~/.zshrc ]; then
    shell_profile=~/.zshrc
  elif [ -f ~/.bashrc ]; then
    shell_profile=~/.bashrc
  elif [ -f ~/.bash_profile ]; then
    shell_profile=~/.bash_profile
  fi

  if [ -n "$shell_profile" ]; then
    # Remove any existing NEXUS_API_KEY line
    grep -v "^export NEXUS_API_KEY=" "$shell_profile" > "${shell_profile}.tmp" 2>/dev/null && mv "${shell_profile}.tmp" "$shell_profile"

    # Add the new key
    echo "export NEXUS_API_KEY='$api_key'" >> "$shell_profile"
    log_success "API key added to $shell_profile"
  fi

  # Export for current session
  export NEXUS_API_KEY="$api_key"

  # Verify the key works
  log_info "Verifying API key..."
  local response=$(curl -s -o /dev/null -w "%{http_code}" -X POST "https://api.adverant.ai/api/memory/recall" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $api_key" \
    -d '{"query": "test", "limit": 1}' \
    --max-time 10 2>/dev/null)

  if [ "$response" = "200" ] || [ "$response" = "201" ]; then
    log_success "API key verified successfully!"
  elif [ "$response" = "401" ]; then
    log_warn "API key verification failed (401). Please check your key is correct."
  else
    log_warn "Could not verify API key (HTTP $response). Please check your internet connection."
  fi

  echo ""
  log_info "To apply the API key in your current terminal, run:"
  echo "  source $shell_profile"
}

# Verify installation
verify_installation() {
  echo ""
  log_info "Verifying installation..."

  local errors=0

  if [ -f ~/.claude/skills/nexus-memory/SKILL.md ]; then
    log_success "Skill file: OK"
  else
    log_error "Skill file: MISSING"
    ((errors++))
  fi

  for hook in store-memory.sh recall-memory.sh auto-recall.sh episode-summary.sh; do
    if [ -x ~/.claude/hooks/$hook ]; then
      log_success "Hook $hook: OK"
    else
      log_error "Hook $hook: MISSING or not executable"
      ((errors++))
    fi
  done

  if [ -f ~/.claude/settings.json ]; then
    log_success "Settings file: OK"
  else
    log_error "Settings file: MISSING"
    ((errors++))
  fi

  if [ $errors -gt 0 ]; then
    log_error "Installation completed with $errors error(s)"
    return 1
  fi

  return 0
}

# Print success message
print_success() {
  echo ""
  echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
  echo -e "${GREEN}               Nexus Memory Installation Complete!                        ${NC}"
  echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
  echo ""
  echo "Automatic Memory Features Enabled:"
  echo "  - Auto-recall: Relevant memories fetched on every prompt"
  echo "  - Auto-store: Every prompt and tool use captured"
  echo "  - Auto-ingest: Files read by Claude auto-ingested to memory"
  echo "  - Episode summaries: Generated every 10 tool uses"
  echo ""
  echo "Manual Commands:"
  echo "  Store:  echo '{\"content\": \"...\", \"event_type\": \"learning\"}' | ~/.claude/hooks/store-memory.sh"
  echo "  Recall: echo '{\"query\": \"...\"}' | ~/.claude/hooks/recall-memory.sh"
  echo ""
  echo "Environment Variables:"
  echo "  NEXUS_VERBOSE=1        Enable debug output"
  echo "  NEXUS_RECALL_LIMIT=10  Number of memories to auto-recall"
  echo "  NEXUS_AUTO_INGEST=0    Disable auto-ingestion of files"
  echo "  NEXUS_FRESHNESS_DAYS=30  Days before document flagged as stale"
  echo ""
  echo "Documentation: https://github.com/adverant/nexus-memory-skill"
  echo ""
}

# Main installation function
main() {
  echo ""
  echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
  echo -e "${BLUE}                    Nexus Memory Installer                                ${NC}"
  echo -e "${BLUE}        Give Your AI Perfect Recall — Across Every Session                ${NC}"
  echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
  echo ""

  check_dependencies

  local source_dir
  source_dir=$(get_source_dir)

  create_directories
  install_files "$source_dir"
  configure_settings
  setup_api_key

  if verify_installation; then
    print_success
  else
    log_error "Installation verification failed. Please check the errors above."
    exit 1
  fi
}

# Run main
main "$@"
