"""Run trusted local or HTTP(S) JavaScript games from Python with Deno or Node.js."""
import json
import os
import shutil
import tempfile
from contextlib import closing
from pathlib import Path
import subprocess


def _source(entry):
    value = str(entry)
    if value.lower().startswith(("https://", "http://", "file://")):
        return value
    return str(Path(entry).resolve())


def describe_game(entry, *, node=None):
    """Read the public game description, including optional features and built-in AIs."""
    return _request({"operation": "describe", "entry": _source(entry)}, node)


def run_match(entry, config, *, decide=None, node=None):
    """Run one headless match. decide(observations, context) returns actions by seat."""
    request = {"operation": "run", "entry": _source(entry), "config": config,
               "policy": decide is not None}
    return _request(request, node, decide)


def _request(request, node, decide=None):
    with closing(_game_messages(request, node)) as messages:
        message = next(messages)
        while message["type"] == "decide":
            if decide is None:
                raise RuntimeError("游戏请求了策略动作")
            actions = decide(message["requests"], message["context"])
            message = messages.send(actions)
        return message["value"]


def _worker_command(bridge, scratch, node):
    if node is not None:
        return [node, str(bridge)]
    try:
        from deno import find_deno_bin
    except ImportError:
        deno = shutil.which("deno")
    else:
        deno = find_deno_bin()
    if deno:
        return [deno, "run", "--no-config", "--no-lock", "--no-prompt", "--allow-read",
                "--allow-net", "--allow-env=MUNDI_SDK_TMPDIR", f"--allow-write={scratch}", str(bridge)]
    node = shutil.which("node")
    if node:
        return [node, str(bridge)]
    raise RuntimeError("请在当前 Python 环境执行 python -m pip install 'deno>=2.9.8,<3' 以安装 Deno")


def _game_messages(request, node, bridge_name="python-bridge.mjs"):
    """Yield each decision and accept its actions, then yield the finished result."""
    bridge = Path(__file__).with_name(bridge_name)
    with tempfile.TemporaryDirectory() as scratch, subprocess.Popen(
        _worker_command(bridge, scratch, node), stdin=subprocess.PIPE, stdout=subprocess.PIPE,
        text=True, encoding="utf-8", env={**os.environ, "MUNDI_SDK_TMPDIR": scratch, "DENO_NO_UPDATE_CHECK": "1"}
    ) as worker:
        def send(message):
            worker.stdin.write(json.dumps(message, allow_nan=False) + "\n")
            worker.stdin.flush()

        try:
            send(request)
            for line in worker.stdout:
                message = json.loads(line)
                if message["type"] == "finished":
                    worker.stdin.close()
                    worker.wait(timeout=5)
                    yield message
                    return
                if message["type"] == "error":
                    raise RuntimeError(message["message"])
                if message["type"] != "decide":
                    raise RuntimeError("收到无法处理的游戏消息")
                actions = yield message
                if not isinstance(actions, dict) or set(actions) != set(message["requests"]):
                    raise ValueError("策略须为本次请求的每个席位返回一个动作")
                send({"type": "actions", "actions": actions})
            raise RuntimeError(f"游戏进程未返回赛果，退出码 {worker.wait()}")
        finally:
            if worker.poll() is None:
                worker.kill()
