#!/bin/bash
# Requirements: curl, sed, jq

OPENROUTER_API_KEY=$(<~/private/openrouter.ai.key)

if [ $? -ge 1 ]; then
  MODEL="$1"
else
  #MODEL="x-ai/grok-4-fast"
  #MODEL="x-ai/grok-4"
  #MODEL="google/gemini-3-flash-preview"
  #MODEL="google/gemini-3-pro-preview"
  #MODEL="anthropic/claude-opus-4.1"
  #MODEL="anthropic/claude-sonnet-4.5"
  MODEL="anthropic/claude-sonnet-4.6"
fi

HISTFILE=/dev/null

echo 'Query (terminate with three empty lines):'
IFS=$'\n'
QUERY=""
while read -e -r line; do
  [[ "$line" =~ ^[:space:]+$ ]] || history -s "$line"
  if [[ "$QUERY" =~ (.+)$'\n'{3}$ ]]; then
    QUERY="${BASH_REMATCH[1]}"
    curl -s -N https://openrouter.ai/api/v1/chat/completions \
      -H "Content-Type: application/json" \
      -H @<( printf "Authorization: Bearer %s" "$OPENROUTER_API_KEY" ) \
      -d'
{
  "model": "'"$MODEL"'",
  "stream": True,
  "messages": [
    {
      "role": "user",
      "content": '"$(jq -n --arg str "$QUERY" '$str')"'
    }
  ]
}' | sed -u 's/^data://; s/^: OPENROUTER PROCESSING//; s/^ \[DONE\]//' | jq -j -r --unbuffered '.choices[]?.delta?.content // "", .usage // "", .error // ""'
    printf "\n"
    QUERY=""
  else
    QUERY="$QUERY$line"$'\n'
  fi
done
