#!/usr/bin/env bash
# OpenRouter API query script for CI/CD workflows
# Usage: ./scripts/openrouter-query.sh "your prompt here" [model]
# Models: qwen/qwen3.6-plus:free | qwen/qwen3-235b-a22b | default: qwen/qwen3.6-plus:free
# Requires: OPENROUTER_API_KEY env var

set -euo pipefail

PROMPT="${1:?Usage: openrouter-query.sh \"prompt\" [model]}"
MODEL="${2:-qwen/qwen3.6-plus:free}"
MAX_TOKENS="${3:-4096}"

if [ -z "${OPENROUTER_API_KEY:-}" ]; then
  echo "ERROR: OPENROUTER_API_KEY not set" >&2
  exit 1
fi

RESPONSE=$(curl -s "https://openrouter.ai/api/v1/chat/completions" \
  -H "Authorization: Bearer $OPENROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -H "HTTP-Referer: https://github.com/mohammadasim224/mawidi" \
  -H "X-Title: Mawidi CI/CD" \
  -d "$(jq -n \
    --arg model "$MODEL" \
    --arg prompt "$PROMPT" \
    --argjson max_tokens "$MAX_TOKENS" \
    '{
      model: $model,
      max_tokens: $max_tokens,
      messages: [
        {role: "user", content: $prompt}
      ]
    }'
  )")

# Extract the response content
echo "$RESPONSE" | jq -r '.choices[0].message.content // .error.message // "ERROR: No response"'
