#!/usr/bin/env bash
# kioku-setup.sh — One-command setup for Kioku Agent Kit
# Usage: bash kioku-setup.sh [--user-id USER_ID]
#
# What it does:
#   1. Check dependencies (Docker, Ollama, Python)
#   2. Start databases (ChromaDB + FalkorDB) via Docker Compose
#   3. Pull embedding model (bge-m3 via Ollama)
#   4. Create ~/.kioku/config.env if not exists
#   5. Run a smoke test

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"

# ── Colors ──
RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; BLUE='\033[0;34m'; NC='\033[0m'
ok()   { echo -e "${GREEN}✅ $*${NC}"; }
warn() { echo -e "${YELLOW}⚠️  $*${NC}"; }
err()  { echo -e "${RED}❌ $*${NC}"; exit 1; }
info() { echo -e "${BLUE}ℹ️  $*${NC}"; }

echo ""
echo "╔══════════════════════════════════════╗"
echo "║     Kioku Agent Kit — Setup          ║"
echo "╚══════════════════════════════════════╝"
echo ""

# ── Args ──
USER_ID="${KIOKU_USER_ID:-}"
while [[ $# -gt 0 ]]; do
  case "$1" in
    --user-id|-u) USER_ID="$2"; shift 2 ;;
    *) shift ;;
  esac
done

if [[ -z "$USER_ID" ]]; then
  echo -n "Enter your Kioku user ID (e.g. 'personal', 'work', your name): "
  read -r USER_ID
  [[ -z "$USER_ID" ]] && USER_ID="personal"
fi
info "User ID: $USER_ID"

# ── Step 1: Check dependencies ──
echo ""
echo "── Step 1: Checking dependencies ──"

command -v python3 >/dev/null 2>&1 || err "Python 3 not found. Install from https://python.org"
PY_VER=$(python3 -c "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')")
[[ "$(echo "$PY_VER >= 3.11" | bc -l)" -eq 1 ]] 2>/dev/null || \
  python3 -c "import sys; sys.exit(0) if sys.version_info >= (3,11) else sys.exit(1)" || \
  err "Python 3.11+ required (found $PY_VER)"
ok "Python $PY_VER"

command -v docker >/dev/null 2>&1 && docker info >/dev/null 2>&1 && ok "Docker" || \
  warn "Docker not found or not running. Vector + Graph search will be unavailable."

HAS_DOCKER=$(command -v docker >/dev/null 2>&1 && docker info >/dev/null 2>&1 && echo "yes" || echo "no")
HAS_OLLAMA=$(command -v ollama >/dev/null 2>&1 && echo "yes" || echo "no")

if [[ "$HAS_OLLAMA" == "yes" ]]; then
  ok "Ollama"
else
  warn "Ollama not found. Semantic search will use fake embeddings."
  warn "Install: https://ollama.com"
fi

# ── Step 2: Start databases ──
echo ""
echo "── Step 2: Starting databases ──"

if [[ "$HAS_DOCKER" == "yes" ]]; then
  if [[ -f "$PROJECT_DIR/docker-compose.yml" ]]; then
    info "Starting kioku-chromadb + kioku-falkordb..."
    cd "$PROJECT_DIR"
    docker compose up -d kioku-chromadb kioku-falkordb 2>&1 | tail -3
    sleep 3
    ok "Databases started"
  else
    warn "docker-compose.yml not found. Skipping database start."
  fi
else
  warn "Skipping database start (Docker not available). CLI will work with BM25 only."
fi

# ── Step 3: Pull embedding model ──
echo ""
echo "── Step 3: Embedding model ──"

if [[ "$HAS_OLLAMA" == "yes" ]]; then
  MODEL="${KIOKU_OLLAMA_MODEL:-bge-m3}"
  if ollama list 2>/dev/null | grep -q "$MODEL"; then
    ok "Model $MODEL already available"
  else
    info "Pulling $MODEL (this may take a few minutes)..."
    ollama pull "$MODEL" && ok "Model $MODEL ready"
  fi
else
  warn "Skipping model pull (Ollama not installed)"
fi

# ── Step 4: Create config ──
echo ""
echo "── Step 4: Configuration ──"

CONFIG_DIR="$HOME/.kioku"
CONFIG_FILE="$CONFIG_DIR/config.env"
mkdir -p "$CONFIG_DIR"

if [[ ! -f "$CONFIG_FILE" ]]; then
  cat > "$CONFIG_FILE" <<EOF
# Kioku Agent Kit — Configuration
# Generated by kioku-setup.sh on $(date -u +"%Y-%m-%d")

KIOKU_USER_ID=$USER_ID

# Anthropic API key (for entity extraction in search)
# Get it at: https://console.anthropic.com
# Leave empty to disable auto entity extraction
KIOKU_ANTHROPIC_API_KEY=

# Database endpoints (defaults match docker-compose.yml)
KIOKU_CHROMA_HOST=localhost
KIOKU_CHROMA_PORT=8001
KIOKU_FALKORDB_HOST=localhost
KIOKU_FALKORDB_PORT=6381

# Embedding model (Ollama)
KIOKU_OLLAMA_BASE_URL=http://localhost:11434
KIOKU_OLLAMA_MODEL=bge-m3
EOF
  ok "Created $CONFIG_FILE"
  warn "Edit $CONFIG_FILE to add your KIOKU_ANTHROPIC_API_KEY"
else
  ok "Config already exists at $CONFIG_FILE"
fi

# ── Step 5: Smoke test ──
echo ""
echo "── Step 5: Smoke test ──"

export KIOKU_USER_ID="$USER_ID"
[[ -f "$CONFIG_FILE" ]] && set -a && source "$CONFIG_FILE" && set +a 2>/dev/null || true

if command -v kioku >/dev/null 2>&1; then
  kioku save "Kioku setup completed successfully" --mood "happy" --tags "setup,test" 2>&1 | \
    grep -E "saved|status|error" | head -3 && ok "Save test passed" || warn "Save test failed"

  RESULTS=$(kioku search "setup test" --limit 1 2>&1 | grep -c "count" || echo "0")
  [[ "$RESULTS" -gt 0 ]] && ok "Search test passed" || warn "Search returned no results (may need a moment)"
else
  warn "kioku command not found. Install with: pip install kioku-agent-kit[full]"
fi

# ── Done ──
echo ""
echo "╔══════════════════════════════════════╗"
echo "║           Setup Complete! 🎉          ║"
echo "╚══════════════════════════════════════╝"
echo ""
echo "Quick start:"
echo "  export KIOKU_USER_ID=$USER_ID"
echo "  kioku save \"Your first memory\" --mood happy"
echo "  kioku search \"memory\""
echo ""
echo "For Claude Code / Cursor:"
echo "  Copy CLAUDE.md to your project root — Claude will auto-discover it."
echo ""
echo "Docs: https://github.com/phuc-nt/kioku-agent-kit"
