#!/usr/bin/env bash

conversation_file=$(mktemp)
echo new conversation: "$conversation_file"
OPENAPI_TOKEN=$(pass openai/api-key)

prompt="You are Mr.Helper. You are an assistant that lives in a floating terminal above my mac. I can summon you with the press of a button! Feel free to use ansii escape codes to add colors or other formatting to your responses."

echo -n "$prompt" | jq -sR '{"role": "system", "content": .}' > "$conversation_file"

bind 'set disable-completion On' 2>/dev/null

printf '\033[48;5;241m\033[38;5;15m'
while read -rep '> ' prompt ; do
  [ -n "$prompt" ] || continue

  echo -n "$prompt" | jq -sR '{"role": "user", "content": .}' >> "$conversation_file"

  messages=$(jq -rsc < "$conversation_file")

  out="$(
    http \
      -A bearer \
      --auth "$OPENAPI_TOKEN" \
      https://api.openai.com/v1/chat/completions \
      model=gpt-3.5-turbo \
      messages:="$messages"
  )"
  reply=$(echo "$out" | jq -rc .choices[0].message)
  echo "$reply" >> "$conversation_file"
  printf '\033[48;5;235m\033[38;5;15m'
  echo "$reply" | jq -rc .content
  printf '\033[48;5;241m\033[38;5;15m'
done
