"""fetch_notes.py - a small stand-in for an agent. It runs inside the sandbox.

    python3 fetch_notes.py                  ask the pretend API for the notes
    python3 fetch_notes.py <an address>     send the same key somewhere else

It knows the name of the variable that holds the key. Watch what is in it.
"""
import os
import sys
import urllib.error
import urllib.request

NOTES = "http://host.openshell.internal:8642/notes"


def main():
    address = sys.argv[1] if len(sys.argv) > 1 else NOTES
    key = os.environ["NOTES_API_KEY"]
    print("the key I hold:", key)
    request = urllib.request.Request(address, headers={"Authorization": "Bearer " + key})
    try:
        with urllib.request.urlopen(request, timeout=15) as reply:
            print("the answer    :", reply.read().decode().strip())
    except urllib.error.HTTPError as refusal:
        print("refused       :", refusal.code, refusal.read().decode().strip())


if __name__ == "__main__":
    main()
