#!/usr/bin/env zsh
set -euo pipefail

script_dir="${0:A:h}"
source "${script_dir}/lib/common.zsh"
source "${script_dir}/lib/json.zsh"

usage='Usage: query_ollama [--json] "prompt" [model]'
inferencer_parse_query_args "$usage" "$@" || exit $?
inferencer_require_command jq
inferencer_require_command curl

api_key="${OLLAMA_API_KEY:-}"
url="${OLLAMA_API_URL:-https://ollama.com/api/chat}"
model="${INFERENCER_MODEL:-${OLLAMA_MODEL:-gpt-oss:120b}}"

inferencer_require_api_key "$api_key" "OLLAMA_API_KEY"

body="$(
  jq -n \
    --arg prompt "$INFERENCER_PROMPT" \
    --arg model "$model" \
    '{
      model: $model,
      messages: [{ role: "user", content: $prompt }],
      stream: false
    }'
)"

response="$(
  curl --silent --show-error --fail \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $api_key" \
    --data "$body" \
    "$url"
)"

if inferencer_response_has_error "$response"; then
  inferencer_print_error_response "$response"
  exit 1
fi

if [[ "$INFERENCER_JSON" == true ]]; then
  printf '%s\n' "$response" | jq .
  exit 0
fi

text="$(printf '%s' "$response" | jq -r '.message.content // empty')"
[[ -n "$text" ]] || {
  print -r -- "Error: Ollama API returned no message content." >&2
  inferencer_print_error_response "$response"
  exit 1
}

printf '%s\n' "$text"
