#!/usr/bin/env python3
import json
import os
import urllib.request

BASE = os.environ.get('POKERAI_BASE_URL', 'https://pokerai.bet').rstrip('/')
KEY = os.environ.get('POKERAI_API_KEY')

def post(path, body):
    request = urllib.request.Request(
        BASE + path,
        data=json.dumps(body).encode(),
        headers={'Authorization': 'Bearer ' + KEY, 'Content-Type': 'application/json'},
        method='POST',
    )
    with urllib.request.urlopen(request) as response:
        return json.load(response)

def check(node):
    return next(child['token'] for child in node['children'] if child.get('action') == 'check' and child.get('token'))

def eq(node):
    result = post('/v1/gto/postflop/cache/eq', {'node': node['token'], 'hole_cards': 'AhKh'})
    assert 'eq' in result and 'token' not in result
    print(json.dumps(result))

root = post('/v1/gto/postflop/cache/query', {
    'board': '4c8d9h', 'pot_type': '3BET',
    'positions': {'hero': 'SB', 'raiser': 'MP', 'three_bettor': 'SB'},
    'preflop_pack': '6max_RC_100bb_200NL', 'hole_cards': 'AhKh',
})
eq(root)

flop_action = post('/v1/gto/postflop/cache/query', {'node': check(root)})
flop_chance = post('/v1/gto/postflop/cache/query', {'node': check(flop_action)})
turn = post('/v1/gto/postflop/cache/query', {'node': flop_chance['token'], 'turn_card': 'As', 'hole_cards': 'AhKh'})
eq(turn)

turn_action = post('/v1/gto/postflop/cache/query', {'node': check(turn)})
turn_chance = post('/v1/gto/postflop/cache/query', {'node': check(turn_action)})
river = post('/v1/gto/postflop/cache/query', {'node': turn_chance['token'], 'river_card': '7d', 'hole_cards': 'AhKh'})
eq(river)
