#!/usr/bin/env python3
"""Direct HTTP, no SDK or automatic retries. Token placeholders are never used.
Run: POKERAI_API_KEY=... python3 postflop_cache_workflow.py [custom_request.json]
Optional POKERAI_BASE_URL selects a controlled local HTTP host for replay.
Fixture source: local-isolated-http, Relay 938d04e708dc8bb5e47c38f330e3397d0851c102.
This example does not establish production deployment or cache coverage.
"""
import json
import os
import sys
from urllib.error import HTTPError
from urllib.request import Request, urlopen

base = os.environ.get("POKERAI_BASE_URL", "https://pokerai.bet").rstrip("/")
key = os.environ["POKERAI_API_KEY"]
root_request = {"board": "AhKhQh", "pot_type": "4BET",
                "positions": {"hero": "UTG", "raiser": "UTG", "three_bettor": "MP"}}
if len(sys.argv) > 1:
    with open(sys.argv[1], encoding="utf-8") as source:
        root_request = json.load(source)


def query(body):
    request = Request(base + "/v1/gto/postflop/cache/query",
                      data=json.dumps(body).encode(), method="POST",
                      headers={"Authorization": "Bearer " + key,
                               "Content-Type": "application/json"})
    try:
        with urlopen(request, timeout=25) as response:
            result = json.load(response)
    except HTTPError as error:
        # A missing receipt does not prove no debit. Never automatically retry.
        raise RuntimeError(f"HTTP {error.code}: {error.read().decode()}") from error
    print(json.dumps(result))
    return result


def child_token(node, action, amount=None):
    matches = [child for child in node["children"]
               if child.get("action") == action and child.get("cached")
               and "token" in child
               and (amount is None or child.get("amount_bb") == amount)]
    if len(matches) != 1:
        raise RuntimeError("Expected exactly one cached action; stop, do not guess a path")
    return matches[0]["token"]


def read_hand(node):
    hand = query({"node": node["token"], "hole_cards": "JdJc"})
    assert "cache_quota" not in hand
    assert hand["is_hero"] and hand["hole_cards"] == "JdJc"
    # StrategyItem.frequency is a mixed frequency; unknown EV/EQ is absent.
    return hand["strategy"]


flop = query(root_request)                         # paid root
read_hand(flop)                                   # free hand
opponent = query({"node": child_token(flop, "bet", 3)})
flop_chance = query({"node": child_token(opponent, "call")})  # optional free preview
assert flop_chance["node_type"] == "chance"
turn = query({"node": flop_chance["token"], "turn_card": "2d"})  # paid Turn
read_hand(turn)
opponent = query({"node": child_token(turn, "check")})
turn_chance = query({"node": child_token(opponent, "check")})   # optional free preview
assert turn_chance["node_type"] == "chance"
river = query({"node": turn_chance["token"], "river_card": "2s"})  # paid River
read_hand(river)
# This isolated fixture uses one unchanged service period/limit. Live bonuses or
# period changes can change the next receipt: always use that request's receipt.
print(json.dumps({"cache_receipts": [node["cache_quota"] for node in [flop, turn, river]]}))
