#!/bin/bash
#
# ELIDA Client Configuration Deployment Script for macOS
#
# This script configures AI coding tools to route through ELIDA.
# Deploy via Jamf, Kandji, Mosyle, or run manually.
#
# Usage:
#   ./deploy-elida-config.sh                    # Uses default ELIDA host
#   ELIDA_HOST="http://proxy:8080" ./deploy-elida-config.sh
#
# For MDM deployment:
#   - Jamf: Upload as a script, run at login or recurring check-in
#   - Kandji: Add as a Custom Script
#   - Mosyle: Add as a Custom Command
#

set -e

# Configuration - Change this to your ELIDA proxy address
ELIDA_HOST="${ELIDA_HOST:-http://elida.corp.local:8080}"

# Detect current user (for MDM context where script runs as root)
if [ "$EUID" -eq 0 ]; then
    CURRENT_USER=$(stat -f "%Su" /dev/console)
    USER_HOME=$(dscl . -read /Users/"$CURRENT_USER" NFSHomeDirectory | awk '{print $2}')
else
    CURRENT_USER=$(whoami)
    USER_HOME="$HOME"
fi

echo "Deploying ELIDA configuration for user: $CURRENT_USER"
echo "ELIDA Host: $ELIDA_HOST"

# -----------------------------------------------------------------------------
# Claude Code CLI
# -----------------------------------------------------------------------------
echo "Configuring Claude Code CLI..."
CLAUDE_DIR="$USER_HOME/.claude"
mkdir -p "$CLAUDE_DIR"
cat > "$CLAUDE_DIR/settings.json" << EOF
{
  "env": {
    "ANTHROPIC_BASE_URL": "$ELIDA_HOST"
  }
}
EOF
chown "$CURRENT_USER" "$CLAUDE_DIR/settings.json" 2>/dev/null || true

# -----------------------------------------------------------------------------
# Continue.dev (VS Code Extension)
# -----------------------------------------------------------------------------
echo "Configuring Continue.dev..."
CONTINUE_DIR="$USER_HOME/.continue"
mkdir -p "$CONTINUE_DIR"
cat > "$CONTINUE_DIR/config.yaml" << EOF
# ELIDA-managed Continue.dev configuration
# Generated by deploy-elida-config.sh

models:
  # Anthropic Claude
  - name: "claude-3-opus"
    provider: "anthropic"
    apiBase: "$ELIDA_HOST"
    apiKey: "\${ANTHROPIC_API_KEY}"

  - name: "claude-3-sonnet"
    provider: "anthropic"
    apiBase: "$ELIDA_HOST"
    apiKey: "\${ANTHROPIC_API_KEY}"

  # OpenAI GPT
  - name: "gpt-4"
    provider: "openai"
    apiBase: "$ELIDA_HOST/v1"
    apiKey: "\${OPENAI_API_KEY}"

  - name: "gpt-4-turbo"
    provider: "openai"
    apiBase: "$ELIDA_HOST/v1"
    apiKey: "\${OPENAI_API_KEY}"

  # Mistral
  - name: "codestral"
    provider: "mistral"
    apiBase: "$ELIDA_HOST/v1"
    apiKey: "\${MISTRAL_API_KEY}"

# Tab autocomplete model
tabAutocompleteModel:
  provider: "openai"
  apiBase: "$ELIDA_HOST/v1"
  apiKey: "\${OPENAI_API_KEY}"
  model: "gpt-4"
EOF
chown "$CURRENT_USER" "$CONTINUE_DIR/config.yaml" 2>/dev/null || true

# -----------------------------------------------------------------------------
# Shell Profile (zsh/bash)
# -----------------------------------------------------------------------------
echo "Configuring shell environment..."
for SHELL_PROFILE in "$USER_HOME/.zshrc" "$USER_HOME/.bashrc" "$USER_HOME/.bash_profile"; do
    if [ -f "$SHELL_PROFILE" ] || [ "$SHELL_PROFILE" = "$USER_HOME/.zshrc" ]; then
        # Remove old ELIDA config if present
        if grep -q "# ELIDA AI Proxy Configuration" "$SHELL_PROFILE" 2>/dev/null; then
            # Use sed to remove the block
            sed -i '' '/# ELIDA AI Proxy Configuration/,/# End ELIDA/d' "$SHELL_PROFILE"
        fi

        # Add new configuration
        cat >> "$SHELL_PROFILE" << EOF

# ELIDA AI Proxy Configuration
# Managed by deploy-elida-config.sh - Do not edit manually
export ANTHROPIC_BASE_URL="$ELIDA_HOST"
export OPENAI_BASE_URL="$ELIDA_HOST/v1"
export OPENAI_API_BASE="$ELIDA_HOST/v1"
export MISTRAL_API_BASE="$ELIDA_HOST"
export LLM_PROXY_URL="$ELIDA_HOST"
# End ELIDA
EOF
        chown "$CURRENT_USER" "$SHELL_PROFILE" 2>/dev/null || true
        echo "  Updated: $SHELL_PROFILE"
    fi
done

# -----------------------------------------------------------------------------
# launchd Environment (for GUI apps)
# -----------------------------------------------------------------------------
echo "Configuring launchd environment..."
LAUNCHD_PLIST="$USER_HOME/Library/LaunchAgents/com.elida.environment.plist"
mkdir -p "$(dirname "$LAUNCHD_PLIST")"
cat > "$LAUNCHD_PLIST" << EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.elida.environment</string>
    <key>ProgramArguments</key>
    <array>
        <string>sh</string>
        <string>-c</string>
        <string>launchctl setenv ANTHROPIC_BASE_URL "$ELIDA_HOST" &amp;&amp; launchctl setenv OPENAI_BASE_URL "$ELIDA_HOST/v1" &amp;&amp; launchctl setenv MISTRAL_API_BASE "$ELIDA_HOST"</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
</dict>
</plist>
EOF
chown "$CURRENT_USER" "$LAUNCHD_PLIST" 2>/dev/null || true

# Load the launchd agent (if not running as root in MDM context)
if [ "$EUID" -ne 0 ]; then
    launchctl unload "$LAUNCHD_PLIST" 2>/dev/null || true
    launchctl load "$LAUNCHD_PLIST"
fi

# -----------------------------------------------------------------------------
# Verification
# -----------------------------------------------------------------------------
echo ""
echo "ELIDA configuration deployed successfully!"
echo ""
echo "Configured tools:"
echo "  - Claude Code CLI (~/.claude/settings.json)"
echo "  - Continue.dev (~/.continue/config.yaml)"
echo "  - Shell environment (~/.zshrc, ~/.bashrc)"
echo "  - launchd environment (for GUI apps)"
echo ""
echo "To apply changes:"
echo "  1. Open a new terminal window, or run: source ~/.zshrc"
echo "  2. Restart any running AI coding tools (Cursor, VS Code, etc.)"
echo ""
echo "Verify configuration:"
echo "  curl $ELIDA_HOST/health"
