#!/usr/bin/env python3
"""Cache EQ workflow available in production since 2026-11-18: coverage, Flop, Turn, River.

The companion JSON is the frozen 2026-11-17 historical production capture.
This program uses the live /eq endpoint, not historical include_eq=true.
Returned tokens are used dynamically. No paid retries.
POKERAI_BASE_URL may point to a controlled transcript server for offline replay.
Each printed elapsed_ms is measured now, not copied from the historical capture.
"""
import json
import os
import time
from urllib.request import Request, urlopen

BASE = os.environ.get("POKERAI_BASE_URL", "https://pokerai.bet").rstrip("/")
KEY = os.environ["POKERAI_API_KEY"]
QUERY = "/v1/gto/postflop/cache/query"
EQ = "/v1/gto/postflop/cache/eq"


def call(label, method, path, body=None):
    headers = {"Authorization": "Bearer " + KEY}
    if body is not None:
        headers["Content-Type"] = "application/json"
    request = Request(BASE + path, method=method, headers=headers,
                      data=None if body is None else json.dumps(body).encode())
    started = time.perf_counter()
    with urlopen(request, timeout=30) as response:
        result = json.load(response)
        status = response.status
    elapsed_ms = round((time.perf_counter() - started) * 1000, 3)
    print(json.dumps({"label": label, "status": status, "elapsed_ms": elapsed_ms,
                      "request": {"method": method, "path": path, "body": body},
                      "response": result}))
    return result


def query(label, body):
    return call(label, "POST", QUERY, body)


def check_child(node):
    matches = [item for item in node["children"]
               if item.get("action") == "check" and item.get("cached") and item.get("token")]
    if len(matches) != 1:
        raise RuntimeError("Expected one returned cached CHECK token; stop, do not construct a path")
    return matches[0]["token"]


def equity(street, node):
    result = call(street + "-eq", "POST", EQ, {"node": node["token"], "hole_cards": "AsAh"})
    if result.get("eq", {}).get("status") != "ok":
        raise RuntimeError("EQ is unavailable; stop before another charged root or deal")


coverage = call("coverage-page-1", "GET",
                "/v1/gto/postflop/cache/coverage?preflop_pack=6max&board=2c2d2h&limit=200")
positions = {"hero": "UTG", "raiser": "UTG", "three_bettor": "MP"}
matches = [item for item in coverage["items"]
           if item.get("preflop_pack") == "6max" and item.get("board") == "2c2d2h"
           and item.get("pot_type") == "4BET" and item.get("positions") == positions]
if len(matches) != 1:
    raise RuntimeError("Expected published preset is not on this page; stop without a paid query")
flop = query("flop-root", {**matches[0], "hole_cards": "AsAh"})
equity("flop", flop)
flop_check = query("flop-check", {"node": check_child(flop)})
flop_chance = query("flop-check-check", {"node": check_child(flop_check)})
turn = query("turn-deal", {"node": flop_chance["token"], "turn_card": "2s", "hole_cards": "AsAh"})
equity("turn", turn)
turn_check = query("turn-check", {"node": check_child(turn)})
turn_chance = query("turn-check-check", {"node": check_child(turn_check)})
river = query("river-deal", {"node": turn_chance["token"], "river_card": "3c", "hole_cards": "AsAh"})
equity("river", river)
