#!/usr/bin/env python3
"""Direct HTTP. Free discovery first; optionally query one explicitly selected item.
Run: POKERAI_API_KEY=... python3 postflop_cache_coverage_discover.py [item-index]
Without an index, only the free directory is read. No paid retries or SDK methods.
Optional POKERAI_BASE_URL selects a controlled loopback replay host.
Example source: local-isolated-http, not a production capture. Board 2c2d2h is
separate from the existing AhKhQh Flop -> Turn -> River strategy capture.
"""
import json
import os
import sys
from urllib.parse import urlencode
from urllib.request import Request, urlopen

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


def discover(filters=None):
    # Preserve original board spelling and explicit filters on every page.
    params = dict({"preflop_pack": "6max", "board": "2c2d2h"} if filters is None else filters)
    params.setdefault("limit", 50)
    items = []
    while True:
        request = Request(BASE + "/v1/gto/postflop/cache/coverage?" + urlencode(params),
                          headers={"Authorization": "Bearer " + KEY})
        with urlopen(request, timeout=25) as response:
            page = json.load(response)
        items.extend(page["items"])
        if page["next_cursor"] is None:
            return items
        # An empty items page with a cursor is not the end.
        params["cursor"] = page["next_cursor"]


def query_selected(item):
    # One paid root request, outside discovery. Builder/Pro and normal charges apply.
    request = Request(BASE + "/v1/gto/postflop/cache/query",
                      data=json.dumps(item).encode(),
                      headers={"Authorization": "Bearer " + KEY,
                               "Content-Type": "application/json"}, method="POST")
    with urlopen(request, timeout=25) as response:
        return json.load(response)


if __name__ == "__main__":
    items = discover()
    print(json.dumps({"items": items}))
    if len(sys.argv) > 1:
        print(json.dumps(query_selected(items[int(sys.argv[1])])) )
    # For returned-node navigation, use the existing postflop_cache_workflow.py
    # and /docs#postflop-cache; its AhKhQh capture is a separate example.
