#!/bin/bash

# === Schraubär 🐻🔧 – Crumbforest Werkzeug-Meister ===
QUESTION="$*"
API_KEY="$OPENROUTER_API_KEY"
MODEL="openai/gpt-4o"

HISTORY_DIR="$HOME/.schraubaer_logs"
HISTORY_FILE="$HISTORY_DIR/schraubaer_history.json"
TOKEN_LOG="$HISTORY_DIR/token_log.json"
TMP_REQUEST="/tmp/schraubaer_request.json"
TMP_RESPONSE="/tmp/schraubaer_response.json"

mkdir -p "$HISTORY_DIR"

SYSTEM_PROMPT="You are Schraubär, the bear of the Crumbforest who teaches children mechanical engineering and tool usage. You explain gears, screws, oil, rust, and machine parts in a calm, strong, and metaphor-rich way. Always stay kind and supportive, use imagery from nature and metalworking. Respond in the same language as the question – German, English, or other."

echo "🐻🔧 Schraubär denkt nach über: $QUESTION"

# Build JSON request
cat > "$TMP_REQUEST" <<EOF
{{
  "model": "$MODEL",
  "temperature": 0.6,
  "messages": [
    {{"role": "system", "content": "$SYSTEM_PROMPT"}},
    {{"role": "user", "content": "$QUESTION"}}
  ]
}}
EOF

# Call OpenRouter API
curl -s https://openrouter.ai/api/v1/chat/completions   -H "Authorization: Bearer $API_KEY"   -H "Content-Type: application/json"   -d @"$TMP_REQUEST" > "$TMP_RESPONSE"

REPLY=$(jq -r '.choices[0].message.content' "$TMP_RESPONSE")

echo -e "\n$REPLY"

# Save to history
if [ -s "$HISTORY_FILE" ]; then
  jq --arg content "$REPLY" '. + [{"role": "assistant", "content": $content}]' "$HISTORY_FILE" > "${HISTORY_FILE}.tmp" && mv "${HISTORY_FILE}.tmp" "$HISTORY_FILE"
else
  echo "[{"role": "assistant", "content": "$REPLY"}]" > "$HISTORY_FILE"
fi

# Save token usage if available
USAGE=$(jq -c '.usage' "$TMP_RESPONSE" 2>/dev/null)
if [ ! -z "$USAGE" ]; then
  echo "{\"zeit\": \"$(date '+%Y-%m-%d %H:%M:%S')\", \"rolle\": \"schraubaer\", \"usage\": "$USAGE"}" >> "$TOKEN_LOG"
fi
