#!/usr/bin/env python3
"""hello-ask "message"  -> asks Hello (127.0.0.1:8096, model Hello) and prints the reply."""
import json, os, sys, urllib.request
if len(sys.argv) < 2 or sys.argv[1] in ("-h", "--help"):
    print(__doc__.strip()); sys.exit(0 if len(sys.argv) > 1 else 2)
key = open(os.path.expanduser("~/.hello/chat.key")).read().strip()
body = json.dumps({"model": "Hello", "messages": [{"role": "user", "content": " ".join(sys.argv[1:])}], "user": os.environ.get("HELLO_ASK_USER", "hello-ask-test")}).encode()
req = urllib.request.Request(os.environ.get("HELLO_CHAT_URL", "http://127.0.0.1:8096") + "/v1/chat/completions", body,
                             {"Content-Type": "application/json", "Authorization": "Bearer " + key})
try:
    with urllib.request.urlopen(req, timeout=300) as r: d = json.load(r)
    print(d["choices"][0]["message"]["content"])
except urllib.error.HTTPError as e:
    print(f"hello-ask: HTTP {e.code}: {e.read().decode(errors='replace')[:300]}", file=sys.stderr); sys.exit(1)
except Exception as e:
    print(f"hello-ask: {e}", file=sys.stderr); sys.exit(1)
