"""Send one real question of the big game, and keep its answer for the page.

    python one_decision.py [address]
    python one_decision.py --from-game       (only in the site's source: see below)

The question is game_question.json, in the folder above this one. It is what the game's
page sends for a gecko that is not tired, with a dragonfly close enough to jump at. It
goes to the address in ask.py unless another one is given, and the answer is written to
game_answer.json. Tutorial 6 shows both files.

The numbers in the answer differ a little from run to run. The pick does not.

--from-game writes game_question.json again, from the request that the game's own check
keeps written out (spark/gecko_game/check_server.py). Use it when the game's words change.
That file is in the site's source and not on the site.
"""
import json
import pathlib
import sys
import urllib.request

ASSETS = pathlib.Path(__file__).resolve().parent.parent      # the tutorial's files: one folder up from checks/
GAME = ASSETS.parent.parent / "spark" / "gecko_game"            # only there in the site's source


def keep(name, content):
    text = json.dumps(content, indent=2, ensure_ascii=False) + "\n"
    (ASSETS / name).write_text(text, encoding="utf-8", newline="\n")


def main():
    sys.path.insert(0, str(ASSETS))
    import ask
    arguments = sys.argv[1:]
    if "--from-game" in arguments:
        arguments.remove("--from-game")
        if not (GAME / "check_server.py").exists():
            print("--from-game needs the site's source: there is no", GAME / "check_server.py")
            return 2
        sys.path.insert(0, str(GAME))
        import check_server
        keep("game_question.json", {"state": check_server.STATE, "questions": {"move": check_server.QUESTION}})
        print("wrote game_question.json from the game's own request")
    address = arguments[0] if arguments else ask.MODEL
    question = json.loads((ASSETS / "game_question.json").read_text(encoding="utf-8"))
    sent = json.dumps(question).encode()
    request = urllib.request.Request(address, sent, {"Content-Type": "application/json"})
    with urllib.request.urlopen(request, timeout=30) as reply:
        received = reply.read()
    answer = json.loads(received)
    keep("game_answer.json", answer)
    move = answer["answers"]["move"]
    print(f"sent {len(sent):,} bytes to {address}")
    print(f"got {len(received):,} bytes: {move['choice']} {move['probabilities']}")
    print("tokens read:", answer["usage"]["input_tokens"], " tokens written:", answer["usage"]["output_tokens"])
    return 0


if __name__ == "__main__":
    sys.exit(main())
