#!/bin/bash
#
# Nexus Memory - API Key Helper
# Shared functions for API key validation and interactive prompting.
#
# Usage:
#   source "$(dirname "$0")/api-key-helper.sh"
#   require_api_key [--interactive]
#
# Functions:
#   require_api_key [--interactive]
#     Checks if NEXUS_API_KEY is set. If --interactive is passed and key is missing,
#     prompts the user to enter it. Exits with code 1 if key is not provided.
#
#   validate_api_key
#     Validates the API key format (must start with 'brain_')
#
#   save_api_key_to_profile
#     Saves the API key to ~/.zshrc or ~/.bashrc for persistence
#

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

# API key storage location
API_KEY_FILE="${HOME}/.claude/session-env/nexus-api-key"
SHELL_PROFILE="${HOME}/.zshrc"

# Ensure session-env directory exists
mkdir -p "${HOME}/.claude/session-env" 2>/dev/null

# Load API key from file if not in environment
load_api_key() {
  if [[ -z "$NEXUS_API_KEY" ]] && [[ -f "$API_KEY_FILE" ]]; then
    NEXUS_API_KEY=$(cat "$API_KEY_FILE" 2>/dev/null)
    export NEXUS_API_KEY
  fi
}

# Validate API key format
validate_api_key() {
  local key="$1"

  if [[ -z "$key" ]]; then
    return 1
  fi

  # API keys should start with 'brain_' and be at least 50 characters
  if [[ "$key" =~ ^brain_[A-Za-z0-9_-]{40,}$ ]]; then
    return 0
  fi

  return 1
}

# Save API key to file (for session persistence)
save_api_key() {
  local key="$1"
  echo "$key" > "$API_KEY_FILE"
  chmod 600 "$API_KEY_FILE"
}

# Prompt user for API key interactively
prompt_for_api_key() {
  echo "" >&2
  echo -e "${YELLOW}╔══════════════════════════════════════════════════════════════════╗${NC}" >&2
  echo -e "${YELLOW}║${NC}                    ${BLUE}Nexus Memory - API Key Required${NC}                ${YELLOW}║${NC}" >&2
  echo -e "${YELLOW}╚══════════════════════════════════════════════════════════════════╝${NC}" >&2
  echo "" >&2
  echo -e "  The Nexus Memory skill requires an API key to function." >&2
  echo "" >&2
  echo -e "  ${GREEN}Get your API key from:${NC}" >&2
  echo -e "    https://dashboard.adverant.ai/dashboard/api-keys" >&2
  echo "" >&2
  echo -e "  ${BLUE}Your API key starts with 'brain_' and looks like:${NC}" >&2
  echo -e "    brain_0rSwBTjulJcY1K-JhrSmRNdA8SfayfziG4s6a6bja4xY2kSDj..." >&2
  echo "" >&2

  # Check if we're in an interactive terminal
  if [[ -t 0 ]]; then
    echo -n "  Enter your API key: " >&2
    read -r api_key

    if [[ -z "$api_key" ]]; then
      echo "" >&2
      echo -e "  ${RED}No API key provided. Operation cancelled.${NC}" >&2
      echo "" >&2
      return 1
    fi

    if ! validate_api_key "$api_key"; then
      echo "" >&2
      echo -e "  ${RED}Invalid API key format. API keys start with 'brain_'.${NC}" >&2
      echo "" >&2
      return 1
    fi

    # Save the key
    save_api_key "$api_key"
    export NEXUS_API_KEY="$api_key"

    echo "" >&2
    echo -e "  ${GREEN}API key saved to ~/.claude/session-env/nexus-api-key${NC}" >&2
    echo "" >&2
    echo -e "  ${BLUE}Tip: For persistence across sessions, add to your shell profile:${NC}" >&2
    echo -e "    echo 'export NEXUS_API_KEY=\"$api_key\"' >> ~/.zshrc" >&2
    echo "" >&2

    return 0
  else
    # Not interactive - show error
    echo -e "  ${RED}Not running in interactive mode.${NC}" >&2
    echo "" >&2
    echo -e "  Set the API key in your environment:" >&2
    echo -e "    export NEXUS_API_KEY='your-api-key-here'" >&2
    echo "" >&2
    return 1
  fi
}

# Main function to require API key
# Usage: require_api_key [--interactive] [--silent]
#   --interactive: Prompt user for key if not set (for user-invoked commands)
#   --silent: Exit silently if key not set (for automatic hooks)
require_api_key() {
  local interactive=0
  local silent=0

  for arg in "$@"; do
    case "$arg" in
      --interactive) interactive=1 ;;
      --silent) silent=1 ;;
    esac
  done

  # Try loading from file first
  load_api_key

  # If we have a key, validate it
  if [[ -n "$NEXUS_API_KEY" ]]; then
    if validate_api_key "$NEXUS_API_KEY"; then
      return 0
    else
      echo -e "${RED}[nexus-memory] Invalid API key format. Key must start with 'brain_'.${NC}" >&2
      if [[ $interactive -eq 1 ]]; then
        prompt_for_api_key
        return $?
      else
        return 1
      fi
    fi
  fi

  # No API key - handle based on mode
  if [[ $silent -eq 1 ]]; then
    # Silent mode - just exit
    exit 0
  elif [[ $interactive -eq 1 ]]; then
    # Interactive mode - prompt for key
    prompt_for_api_key
    return $?
  else
    # Default - show error message
    echo -e "${RED}[nexus-memory] ERROR: NEXUS_API_KEY is required but not set.${NC}" >&2
    echo "" >&2
    echo "  Get your API key from: https://dashboard.adverant.ai/dashboard/api-keys" >&2
    echo "" >&2
    echo "  Set it in your environment:" >&2
    echo "    export NEXUS_API_KEY='your-api-key-here'" >&2
    echo "" >&2
    return 1
  fi
}
