#!/bin/bash
# AI Tools Overlay
# Adds: Alternative AI coding assistants (OpenCode, Crush)
#
# Tools:
#   opencode - AI coding agent (Go-based, opencode-ai)
#   crush    - Glamorous AI coding agent (Charmbracelet)
#
# Usage: Called by dev.sh during container creation
#   apply_ai-tools_overlay <container_name>

set -e

OVERLAY_NAME="ai-tools"

apply_ai-tools_overlay() {
    local container="$1"

    echo "[OVERLAY] Applying AI tools overlay to $container..."

    sudo machinectl shell "$container" /bin/bash -c '
# Install common dependencies
DEBIAN_FRONTEND=noninteractive apt-get install -y \
    curl \
    ca-certificates \
    gnupg \
    ripgrep \
    fd-find

# --- Install OpenCode ---
echo "Installing OpenCode..."
curl -fsSL https://raw.githubusercontent.com/opencode-ai/opencode/refs/heads/main/install | bash
# Move to system path if installed to user dir
[ -f /root/.local/bin/opencode ] && mv /root/.local/bin/opencode /usr/local/bin/ || true

# --- Install Crush (Charmbracelet) ---
echo "Installing Crush..."
# Add Charm APT repository
mkdir -p /etc/apt/keyrings
curl -fsSL https://repo.charm.sh/apt/gpg.key | gpg --dearmor -o /etc/apt/keyrings/charm.gpg
echo "deb [signed-by=/etc/apt/keyrings/charm.gpg] https://repo.charm.sh/apt/ * *" > /etc/apt/sources.list.d/charm.list
apt-get update
DEBIAN_FRONTEND=noninteractive apt-get install -y crush

# Verify installations
echo ""
echo "Installed AI tools:"
opencode --version 2>/dev/null && echo "  opencode: $(which opencode)" || echo "  opencode: not found"
crush --version 2>/dev/null && echo "  crush: $(which crush)" || echo "  crush: not found"
'

    # Setup for dev user
    sudo machinectl shell "$container" /bin/bash -c '
# Create config directories
mkdir -p /home/dev/.config/opencode /home/dev/.config/crush
chown -R dev:dev /home/dev/.config/opencode /home/dev/.config/crush

# Add helpful aliases
cat >> /home/dev/.bashrc << '\''BASHRC'\''

# AI coding tools
alias oc="opencode"
alias cr="crush"
BASHRC
'

    echo "[OVERLAY] AI tools overlay applied (opencode, crush)"
    echo "[NOTE] Configure API keys in ~/.config/opencode/ and ~/.config/crush/"
}

# Allow sourcing or direct execution
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    if [ -z "$1" ]; then
        echo "Usage: $0 <container_name>"
        exit 1
    fi
    apply_ai-tools_overlay "$1"
fi
