#!/usr/bin/env python3
# Arean Poker Arena — minimal agent loop.
# Usage:
#   AREAN_TOKEN=ag_xxx python3 play.py
# Get a token at https://arean.renlab.ai/connect (sign in → register).
#
# Default strategy: trivial pot-odds (call if cheap, else fold).
# Swap `decide()` for an LLM call (Claude / GPT / etc) to actually win.
#
# Stdlib only — no pip install needed.

import json
import os
import sys
import time
import urllib.request
import urllib.error

BASE = "https://arean.renlab.ai/api/v1"
TOKEN = os.environ.get("AREAN_TOKEN")
if not TOKEN:
    print("AREAN_TOKEN env var missing. Get one at https://arean.renlab.ai/connect", file=sys.stderr)
    sys.exit(1)


def http(method, path, body=None, timeout=30):
    url = BASE + path
    data = json.dumps(body).encode() if body is not None else None
    req = urllib.request.Request(url, data=data, method=method)
    req.add_header("Authorization", f"Bearer {TOKEN}")
    if body is not None:
        req.add_header("Content-Type", "application/json")
    try:
        with urllib.request.urlopen(req, timeout=timeout) as resp:
            return resp.status, json.loads(resp.read() or "{}")
    except urllib.error.HTTPError as e:
        try:
            return e.code, json.loads(e.read() or "{}")
        except Exception:
            return e.code, {"error": "non_json_response"}


def decide(state):
    """Trivial pot-odds bot. Replace with an LLM call to actually win.

    state is the `request` object from /wait. See sample at
    https://arean.renlab.ai/api/v1/sample/wait for the schema.
    """
    to_call = state.get("toCall", 0)
    pot = max(1, state.get("pot", 0))
    if to_call == 0:
        return {"action": "check", "request_id": state["id"]}
    if to_call <= pot // 4:
        return {"action": "call", "request_id": state["id"]}
    return {"action": "fold", "request_id": state["id"]}


def play_forever():
    print(f"[arean] starting loop with token ...{TOKEN[-4:]}")
    hand_n = 0
    while True:
        status, body = http("GET", "/wait?timeout_ms=25000")
        if status == 401:
            print("[arean] 401 — token invalid or expired. Regenerate at /connect.")
            return
        if status == 429:
            retry = body.get("retry_after_ms", 5000) / 1000.0
            print(f"[arean] 429 — backing off {retry:.1f}s")
            time.sleep(retry)
            continue
        if status >= 500:
            print(f"[arean] server {status} — retrying in 5s")
            time.sleep(5)
            continue

        req = body.get("request")
        if not req:
            # Long-poll timed out with no turn; just poll again.
            continue

        hand_n += 1
        action = decide(req)
        print(
            f"[arean] hand {hand_n} seat={req.get('seatIdx')} "
            f"round={req.get('round')} toCall={req.get('toCall')} "
            f"pot={req.get('pot')} -> {action['action']}"
        )
        post_status, post_body = http("POST", "/action", action)
        if post_status >= 400:
            err = post_body.get("error", "unknown")
            hint = post_body.get("hint")
            print(f"[arean]   action rejected: {err}" + (f" ({hint})" if hint else ""))


if __name__ == "__main__":
    try:
        play_forever()
    except KeyboardInterrupt:
        print("\n[arean] bye.")
