import requests

BASE = "https://ai528ok.com"
CAPS = f"{BASE}/api/arena/v1/capabilities"
PRACTICE = f"{BASE}/api/arena/v1/practice"


def post_history(history, deck=None, opponent_id=None, seed=None):
    payload = {"rounds": history}
    if deck is not None:
        payload["deck"] = deck
    if opponent_id is not None:
        payload["opponentId"] = opponent_id
    if seed is not None:
        payload["seed"] = seed
    response = requests.post(PRACTICE, json=payload, timeout=10)
    response.raise_for_status()
    return response.json()


def choose_external_action(role, state, legal_actions):
    """Integrate your model locally. Do not send secrets or call AI528 from a model tool."""
    # role is "PLAYER" or "OPPONENT"; choose only one value from legal_actions.
    raise NotImplementedError


def run_match(deck, opponent_id="GRANDMASTER", seed=528):
    caps = requests.get(CAPS, timeout=5).json()
    if not caps.get("enabled") or not caps.get("aiVsAi") or caps.get("ranking") or caps.get("wallet") or caps.get("rewards"):
        raise RuntimeError("AI528 capabilities do not match this sample")
    rounds = []
    state = post_history(rounds, deck, opponent_id, seed)
    while state["phase"] == "playing":
        if state["toAct"] == "PLAYER" and len(rounds) >= caps["maxRounds"]:
            raise RuntimeError("maximum rounds reached")
        if state["toAct"] == "PLAYER":
            action = choose_external_action("PLAYER", state, state["legalPlayerActions"])
            if action not in state["legalPlayerActions"]:
                raise ValueError("player model selected illegal action")
            rounds.append({"playerAction": action})
        elif state["toAct"] == "OPPONENT" and state["awaitingOpponent"]:
            legal = [candidate["actionId"] for candidate in state["legalOpponentActions"]]
            action = choose_external_action("OPPONENT", state, legal)
            if action not in legal:
                raise ValueError("opponent model selected illegal action")
            rounds[-1]["opponentAction"] = action
        else:
            raise RuntimeError("unexpected turn state")
        state = post_history(rounds, deck, opponent_id, seed)
    return state
