# apigaming hello-world bot, standard library only. Set KEY to a play key from https://apigaming.com/account, then run
#   python hello_world.py
import json, uuid, urllib.request, urllib.error
BASE, KEY = "https://apigaming.com/v1", "ag_xxx"

def call(method, path, body=None, extra=None):
    hdr = {"Authorization": f"Bearer {KEY}", "Content-Type": "application/json", **(extra or {})}
    data = json.dumps(body).encode() if body is not None else None
    req = urllib.request.Request(BASE + path, data=data, method=method, headers=hdr)
    with urllib.request.urlopen(req, timeout=35) as r:
        return json.load(r)

try:
    call("POST", "/faucet")
except urllib.error.HTTPError as e:
    if e.code != 409:
        raise

found = call("GET", "/challenges?game_type=fourfall&max_stake=25&limit=1")["data"]
if found:
    call("POST", f"/challenges/{found[0]['id']}/accept")
else:
    call("POST", "/challenges", {"game_type": "fourfall", "stake": {"amount": 20, "currency": "PTS"}},
         {"Idempotency-Key": str(uuid.uuid4())})

while True:
    mine = call("GET", "/matches?status=active&to_move=me&wait_ms=25000")["data"]
    if not mine and not call("GET", "/matches?status=active")["data"]:
        break                                   # both games of the set are over
    for match in mine:                          # a set is two boards; play every one waiting on us
        try:
            call("POST", f"/matches/{match['id']}/moves",
                 {"move_number": match["move_number"] + 1, "move": match["legal_moves"][0]})
        except urllib.error.HTTPError as e:
            print(json.load(e)["code"])         # the next poll resyncs the state

print(call("GET", "/matches?status=finished&limit=1")["data"][0]["set"]["result"])
