#!/bin/sh
# chance-soul — call any member of the family by name from any shell.
#   chance-soul selah "how do we make the porch feel like home?"
#   chance-soul plutus "what are buyers actually paying for?"
#   chance-soul --raw chance "unfiltered, thinking tags included"
# The wolfpack IS the system — this is its mouth.
SOUL="${1:-chance}"
[ "$SOUL" = "--raw" ] && { RAW=1; SOUL="${2:-chance}"; shift 2 2>/dev/null; }
shift 2>/dev/null
PROMPT="$*"
[ -z "$PROMPT" ] && { echo "usage: chance-soul <soul> \"question\"  (souls: $(ls /usr/local/share/chanceos/souls 2>/dev/null | tr '\n' ' '))"; exit 1; }

SOULDIR="/usr/local/share/chanceos/souls/$SOUL"
SYSTEM=""
if [ -r "$SOULDIR/system.md" ]; then
  SYSTEM=$(cat "$SOULDIR/system.md")
else
  echo "chance-soul: no such soul: $SOUL" >&2
  echo "the pack: $(ls /usr/local/share/chanceos/souls 2>/dev/null | tr '\n' ' ')" >&2
  exit 1
fi

PYCODE=$(cat <<'EOF'
import json, re, sys, urllib.request
up = "http://127.0.0.1:11435"
soul, prompt, syspath = sys.argv[1], sys.argv[2], sys.argv[3]
system = open(syspath).read() if syspath != "-" else ""
msgs = []
if system:
    msgs.append({"role": "system", "content": system})
msgs.append({"role": "user", "content": prompt})
body = json.dumps({"model": "family-base", "messages": msgs, "stream": False,
                   "options": {"num_predict": 320}}).encode()
req = urllib.request.Request(up + "/api/chat", data=body,
                             headers={"Content-Type": "application/json"})
try:
    with urllib.request.urlopen(req, timeout=900) as r:
        out = json.loads(r.read().decode())
except Exception as e:
    print("chance-soul: the pack is quiet — %s" % e, file=sys.stderr)
    sys.exit(2)
text = (out.get("message") or {}).get("content", "")
if "--raw" not in sys.argv:
    text = re.sub(r"</think>.*?</think>", "", text, flags=re.S)
    text = text.split("</think>", 1)[1].strip() if "</think>" in text else text.strip()
    if not text:
        text = (out.get("message") or {}).get("content", "")
print(text)
EOF
)
exec python3 -c "$PYCODE" "$SOUL" "$PROMPT" "$SOULDIR/system.md" --raw