#!/bin/bash
#
# Context Recall Setup Script
# One-command setup for Claude Code context recall system
#
# Usage: bash scripts/setup-context-recall.sh
#

set -e

echo "=========================================="
echo "Claude Code Context Recall Setup"
echo "=========================================="
echo ""

# Detect project root
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
HOOKS_DIR="$PROJECT_ROOT/.claude/hooks"
CONFIG_FILE="$PROJECT_ROOT/.claude/context-recall-config.env"

echo "Project root: $PROJECT_ROOT"
echo ""

# Step 1: Check API availability
echo "[1/7] Checking API availability..."
API_URL="${CLAUDE_API_URL:-http://localhost:8000}"

if ! curl -s --max-time 3 "$API_URL/health" >/dev/null 2>&1; then
    echo "[ERROR] ERROR: API is not available at $API_URL"
    echo ""
    echo "Please start the API server first:"
    echo "  cd $PROJECT_ROOT"
    echo "  uvicorn api.main:app --reload"
    echo ""
    exit 1
fi

echo "[OK] API is running at $API_URL"
echo ""

# Step 2: Get credentials
echo "[2/7] Setting up authentication..."
echo ""
echo "Enter API credentials:"
read -p "Username [admin]: " API_USERNAME
API_USERNAME="${API_USERNAME:-admin}"

read -sp "Password: " API_PASSWORD
echo ""

if [ -z "$API_PASSWORD" ]; then
    echo "[ERROR] ERROR: Password is required"
    exit 1
fi

# Step 3: Get JWT token
echo ""
echo "[3/7] Obtaining JWT token..."

LOGIN_RESPONSE=$(curl -s -X POST "$API_URL/api/auth/login" \
    -H "Content-Type: application/json" \
    -d "{\"username\": \"$API_USERNAME\", \"password\": \"$API_PASSWORD\"}" 2>/dev/null)

JWT_TOKEN=$(echo "$LOGIN_RESPONSE" | grep -o '"access_token":"[^"]*' | sed 's/"access_token":"//')

if [ -z "$JWT_TOKEN" ]; then
    echo "[ERROR] ERROR: Failed to obtain JWT token"
    echo "Response: $LOGIN_RESPONSE"
    exit 1
fi

echo "[OK] JWT token obtained"
echo ""

# Step 4: Get or create project
echo "[4/7] Detecting project..."

# Try to get project from git config
PROJECT_ID=$(git config --local claude.projectid 2>/dev/null || echo "")

if [ -z "$PROJECT_ID" ]; then
    # Try to find project by name
    PROJECT_NAME=$(basename "$PROJECT_ROOT")

    echo "Searching for project: $PROJECT_NAME"

    PROJECTS_RESPONSE=$(curl -s "$API_URL/api/projects" \
        -H "Authorization: Bearer $JWT_TOKEN" 2>/dev/null)

    PROJECT_ID=$(echo "$PROJECTS_RESPONSE" | python3 -c "
import sys, json
try:
    projects = json.load(sys.stdin)
    if isinstance(projects, list):
        for p in projects:
            if p.get('name') == '$PROJECT_NAME':
                print(p.get('id', ''))
                break
except:
    pass
" 2>/dev/null)

    if [ -z "$PROJECT_ID" ]; then
        echo "Project not found. Creating new project..."

        GIT_REMOTE=$(git config --get remote.origin.url 2>/dev/null || echo "")

        CREATE_PAYLOAD=$(cat <<EOF
{
    "name": "$PROJECT_NAME",
    "description": "Auto-created by context recall setup",
    "project_type": "development",
    "metadata": {
        "git_remote": "$GIT_REMOTE",
        "setup_date": "$(date -u +"%Y-%m-%dT%H:%M:%SZ")"
    }
}
EOF
)

        CREATE_RESPONSE=$(curl -s -X POST "$API_URL/api/projects" \
            -H "Authorization: Bearer $JWT_TOKEN" \
            -H "Content-Type: application/json" \
            -d "$CREATE_PAYLOAD" 2>/dev/null)

        PROJECT_ID=$(echo "$CREATE_RESPONSE" | grep -o '"id":"[^"]*' | sed 's/"id":"//')

        if [ -z "$PROJECT_ID" ]; then
            echo "[ERROR] ERROR: Failed to create project"
            echo "Response: $CREATE_RESPONSE"
            exit 1
        fi

        echo "[OK] Project created: $PROJECT_ID"
    else
        echo "[OK] Project found: $PROJECT_ID"
    fi

    # Save to git config
    git config --local claude.projectid "$PROJECT_ID"
    echo "[OK] Project ID saved to git config"
else
    echo "[OK] Project ID from git config: $PROJECT_ID"
fi

echo ""

# Step 5: Configure environment
echo "[5/7] Updating configuration..."

# Backup existing config if it exists
if [ -f "$CONFIG_FILE" ]; then
    cp "$CONFIG_FILE" "$CONFIG_FILE.backup"
    echo "[OK] Backed up existing config to $CONFIG_FILE.backup"
fi

# Write new config
cat > "$CONFIG_FILE" <<EOF
# Claude Code Context Recall Configuration
# Auto-generated by setup-context-recall.sh on $(date)

# API Configuration
CLAUDE_API_URL=$API_URL

# Project Identification
CLAUDE_PROJECT_ID=$PROJECT_ID

# Authentication
JWT_TOKEN=$JWT_TOKEN

# Context Recall Settings
CONTEXT_RECALL_ENABLED=true
MIN_RELEVANCE_SCORE=5.0
MAX_CONTEXTS=10

# Context Storage Settings
AUTO_SAVE_CONTEXT=true
DEFAULT_RELEVANCE_SCORE=7.0

# Debug Settings
DEBUG_CONTEXT_RECALL=false
EOF

echo "[OK] Configuration saved to $CONFIG_FILE"
echo ""

# Step 6: Make hooks executable
echo "[6/7] Setting up hooks..."

if [ -f "$HOOKS_DIR/user-prompt-submit" ]; then
    chmod +x "$HOOKS_DIR/user-prompt-submit"
    echo "[OK] Made user-prompt-submit executable"
else
    echo "[WARNING] Warning: user-prompt-submit not found"
fi

if [ -f "$HOOKS_DIR/task-complete" ]; then
    chmod +x "$HOOKS_DIR/task-complete"
    echo "[OK] Made task-complete executable"
else
    echo "[WARNING] Warning: task-complete not found"
fi

echo ""

# Step 7: Test the system
echo "[7/7] Testing context recall..."

TEST_RECALL_URL="$API_URL/api/conversation-contexts/recall?project_id=$PROJECT_ID&limit=5&min_relevance_score=0.0"

RECALL_RESPONSE=$(curl -s --max-time 3 \
    "$TEST_RECALL_URL" \
    -H "Authorization: Bearer $JWT_TOKEN" 2>/dev/null)

if [ $? -eq 0 ]; then
    CONTEXT_COUNT=$(echo "$RECALL_RESPONSE" | grep -o '"id"' | wc -l)
    echo "[OK] Context recall working (found $CONTEXT_COUNT existing contexts)"
else
    echo "[WARNING] Warning: Context recall test failed (this is OK for new projects)"
fi

echo ""
echo "=========================================="
echo "Setup Complete!"
echo "=========================================="
echo ""
echo "Configuration:"
echo "  API URL: $API_URL"
echo "  Project ID: $PROJECT_ID"
echo "  Config file: $CONFIG_FILE"
echo ""
echo "Next steps:"
echo "  1. Start using Claude Code normally"
echo "  2. Context will be automatically recalled before each message"
echo "  3. Context will be automatically saved after task completion"
echo ""
echo "To test the system:"
echo "  bash scripts/test-context-recall.sh"
echo ""
echo "To view configuration:"
echo "  cat .claude/context-recall-config.env"
echo ""
echo "For help and troubleshooting:"
echo "  cat .claude/hooks/README.md"
echo ""

# Add config to .gitignore if not already there
if ! grep -q "context-recall-config.env" "$PROJECT_ROOT/.gitignore" 2>/dev/null; then
    echo ""
    echo "[WARNING] IMPORTANT: Adding config to .gitignore..."
    echo ".claude/context-recall-config.env" >> "$PROJECT_ROOT/.gitignore"
    echo "[OK] Config file will not be committed (contains JWT token)"
fi

echo ""
echo "Setup complete!"
echo ""
