#!/bin/bash
#
# ClaudeTools New Machine Setup
# Quick setup for new machines (30 seconds)
#
# Usage: bash scripts/setup-new-machine.sh
#

set -e

echo "=========================================="
echo "ClaudeTools New Machine Setup"
echo "=========================================="
echo ""

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

echo "Project root: $PROJECT_ROOT"
echo ""

# Check if template exists in shared data
SHARED_TEMPLATE="C:/Users/MikeSwanson/claude-projects/shared-data/context-recall-config.env"

if [ ! -f "$SHARED_TEMPLATE" ]; then
    echo "[ERROR] ERROR: Template not found at $SHARED_TEMPLATE"
    exit 1
fi

# Copy template
echo "[1/3] Copying configuration template..."
cp "$SHARED_TEMPLATE" "$CONFIG_FILE"
echo "[OK] Configuration file created"
echo ""

# Get project ID from git
echo "[2/3] Detecting project ID..."
PROJECT_ID=$(git config --local claude.projectid 2>/dev/null || echo "")

if [ -z "$PROJECT_ID" ]; then
    # Generate from git remote
    GIT_REMOTE=$(git config --get remote.origin.url 2>/dev/null || echo "")
    if [ -n "$GIT_REMOTE" ]; then
        PROJECT_ID=$(echo -n "$GIT_REMOTE" | md5sum | cut -d' ' -f1)
        git config --local claude.projectid "$PROJECT_ID"
        echo "[OK] Generated project ID: $PROJECT_ID"
    else
        echo "[WARNING] Could not detect project ID"
    fi
else
    echo "[OK] Project ID: $PROJECT_ID"
fi

# Update config with project ID
if [ -n "$PROJECT_ID" ]; then
    sed -i "s|CLAUDE_PROJECT_ID=.*|CLAUDE_PROJECT_ID=$PROJECT_ID|" "$CONFIG_FILE"
fi

echo ""

# Get JWT token
echo "[3/3] Obtaining JWT token..."
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 required"
    exit 1
fi

JWT_TOKEN=$(curl -s -X POST http://172.16.3.30:8001/api/auth/login \
    -H "Content-Type: application/json" \
    -d "{\"username\": \"$API_USERNAME\", \"password\": \"$API_PASSWORD\"}" | \
    grep -o '"access_token":"[^"]*' | sed 's/"access_token":"//')

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

# Update config with token
sed -i "s|JWT_TOKEN=.*|JWT_TOKEN=$JWT_TOKEN|" "$CONFIG_FILE"

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

echo "=========================================="
echo "Setup Complete!"
echo "=========================================="
echo ""
echo "Configuration file: $CONFIG_FILE"
echo "API URL: http://172.16.3.30:8001"
echo "Project ID: $PROJECT_ID"
echo ""
echo "You can now use Claude Code normally."
echo "Context will be automatically recalled from the central server."
echo ""
