#!/bin/bash

# Schnecki – the kind mechanical engineering expert of Crumbforest
QUESTION="$*"
API_KEY="${OPENROUTER_API_KEY}"
MODEL="openai/gpt-3.5-turbo"
LOG_DIR="$HOME/.schnecki_logs"
HISTORY_FILE="$LOG_DIR/schnecki_history.json"
TOKEN_LOG="$LOG_DIR/token_log.json"
TMP_REQUEST="/tmp/schnecki_request.json"
TMP_RESPONSE="/tmp/schnecki_response.json"

mkdir -p "$LOG_DIR"

SYSTEM_PROMPT="You are Schnecki, the Crumbforest's expert in mechanical engineering and tools. You explain things with patience and clarity, using child-friendly metaphors, poetic structure, and solid mechanical insight. You respond in the language of the question, primarily German."

echo "🔧 Schnecki denkt nach: $QUESTION"

jq -n --arg system "$SYSTEM_PROMPT" --arg user "$QUESTION" '{
  model: "openai/gpt-3.5-turbo",
  messages: [
    {role: "system", content: $system},
    {role: "user", content: $user}
  ]
}' > "$TMP_REQUEST"

curl https://openrouter.ai/api/v1/chat/completions   -sS -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🌀 Schnecki sagt:
$REPLY"

# Save response to history
jq -n --arg content "$REPLY" '{"role":"assistant","content":$content}' > "$LOG_DIR/new_entry.json"

# Append to history JSON array
if [ ! -f "$HISTORY_FILE" ]; then
  echo "[]" > "$HISTORY_FILE"
fi
jq '. + [input]' "$HISTORY_FILE" "$LOG_DIR/new_entry.json" > "$HISTORY_FILE.tmp" && mv "$HISTORY_FILE.tmp" "$HISTORY_FILE"

# Token log (if available)
TOKENS=$(jq '.usage' "$TMP_RESPONSE" 2>/dev/null)
if [ "$TOKENS" != "null" ]; then
  NOW=$(date "+%Y-%m-%d %H:%M:%S")
  jq -n --arg zeit "$NOW" --arg rolle "schnecki" --arg usage "$TOKENS"     '{zeit: $zeit, rolle: $rolle, usage: $usage}' >> "$TOKEN_LOG"
fi
