#!/usr/bin/bash
# bare plugin: :ask <question>
# Ask AI a question and get a conversational response.
#
# Setup:
#   1. Get an API key from https://console.anthropic.com/
#   2. Store it in a file: echo "sk-ant-..." > ~/.config/bare/anthropic_key
#   3. Or set the environment variable: export ANTHROPIC_API_KEY="sk-ant-..."
#   4. Copy this file to ~/.bare/plugins/ask and chmod +x it
#
# Usage:
#   :ask how do I find large files?
#   :ask what does the -R flag do in grep?

set -e

# Read API key
if [ -n "$ANTHROPIC_API_KEY" ]; then
    API_KEY="$ANTHROPIC_API_KEY"
elif [ -f "$HOME/.config/bare/anthropic_key" ]; then
    API_KEY=$(cat "$HOME/.config/bare/anthropic_key" | tr -d '\n')
elif [ -f "/home/.safe/anthropic.txt" ]; then
    API_KEY=$(cat "/home/.safe/anthropic.txt" | tr -d '\n')
else
    echo "No API key found. Set ANTHROPIC_API_KEY or create ~/.config/bare/anthropic_key"
    exit 1
fi

QUESTION="$*"
if [ -z "$QUESTION" ]; then
    echo "Usage: :ask <question>"
    exit 1
fi

# Escape JSON
ESCAPED=$(echo "$QUESTION" | sed 's/\\/\\\\/g; s/"/\\"/g; s/\n/\\n/g')

RESPONSE=$(curl -s https://api.anthropic.com/v1/messages \
    -H "Content-Type: application/json" \
    -H "x-api-key: $API_KEY" \
    -H "anthropic-version: 2023-06-01" \
    -d "{
        \"model\": \"claude-haiku-4-5-20251001\",
        \"max_tokens\": 512,
        \"system\": \"You are a helpful terminal assistant. Give concise, practical answers. Use examples when helpful. Keep responses under 10 lines.\",
        \"messages\": [
            {\"role\": \"user\", \"content\": \"$ESCAPED\"}
        ]
    }" 2>/dev/null)

# Extract text from Anthropic response
echo "$RESPONSE" | grep -o '"text":"[^"]*"' | head -1 | sed 's/"text":"//;s/"$//' | sed 's/\\n/\n/g; s/\\"/"/g; s/\\\\/\\/g'
