#!/usr/bin/env bash
if [ $# -lt 1 ]; then
  echo "Usage: $0 <Document>"
  exit 1
fi
MODEL="cogito:32b"
DOC=$(jq -Rs . <"$1" | sed 's/^"/"```json\\n/;s/"$/\\n```\\n"/') # Anführungszeichen escapen
SYSTEM=$(
  jq -Rs . <<'EOF'
Enable deep thinking subroutine.

We are reading a scientific paper.
Please create a conceptual graphviz-diagram (using sfdp for a mindmap-like layout, setting overlap=scale). You can also use a different style within a note (as subgraph) - but only if you have a good reason for it. Use as many depth-layers as neccessary and refrain from using visible subgraphs as "collection of nodes". Also make sure all nodes are connected, are roughly sqare (i.e. **break long labels of text**) and don't overlap.

The root-node with the paper title should be a filled elipse in the center with a light gray filling.

Then define distinct base-colors for all branches of the root-node (the "concepts"). Use subtle colors-shifts within those base-colors in the (grand-)child nodes according to their "feel" (i.e. reddish for negative connotations, greenish for positive connotation, blueish for technical things, purple for social things, etc.). Like in a blue theme (i.e. tech stack) only a reddish-blue or a greenish-blue (mix of target hue into the base-color, while keeping lightness the same). Only use one consistent mix for each base-color with feel-color. Do not use red/green/blue/purple as base-colors. All base-colors should be very distinct (i.e. differ in hue by at least 20%)

Main result should be a **clear**, **concise** and **informative** graphic. You may also add a further level of leafs with more detailed information in smaller print (like cites, quotes, ...), as this is to be used as SVG and can be zoomed in, if needed.

Return your result as plain graphviz code-block without explanations. It will be used by automatic processing and has to be perfect. Use at least 2 levels of nodes.
All in all: Think beforehand what nodes you want, how they connect and when generating use "r", "r_1", "r_2_1" etc for root->branch->branch to not have name conflicts with reserved keywords (i.e. "graph", "node", ..). Also put captions in boxes properly (i.e. ["foo"] for a box with label foo).
You have only one shot. Think extensively if need be.
EOF
)

tmpfile=$(mktemp)
svgfile="$1.svg"

curl -s http://gpu.dighist.geschichte.hu-berlin.de:11434/api/chat -d '{
  "model": "'"$MODEL"'",
  "messages": [
    { "role": "system", "content": '"$SYSTEM"' },
    { "role": "user",
      "content": "This is the document:" },
    { "role": "user",
      "content": '"$DOC"' }
  ],
  "options": {
    "num_ctx":     50000,
    "num_predict": 20000,
    "num_batch": 64,
    "num_keep": 768
  },
  "stream": true
}' | stdbuf -oL jq -crj '.message.content' | tee "$tmpfile"

dotfile=$(mktemp)
awk '/^```/{f = !f; next} f' "$tmpfile" >"$dotfile"
dot -Tsvg -o "$svgfile" "$dotfile"

rm "$tmpfile" "$dotfile"
