"""Small read-only probe for the documented Unreal Editor TCP examples."""
import argparse
import json
import socket
import struct
import time

parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("command", choices=["ping", "get_version", "get_world_info", "get_scene_tree"])
parser.add_argument("--port", type=int, default=9800)
args = parser.parse_args()
request = {"id": "docs-editor-probe", "cmd": args.command}
if args.command == "get_scene_tree":
    request["args"] = {"depth": 1}
payload = json.dumps(request).encode("utf-8")

# A connection may close before the read-only response arrives. Reconnect only
# for a transport failure and only for one of the allowlisted read operations.
for attempt in range(5):
    try:
        with socket.create_connection(("127.0.0.1", args.port), timeout=3) as sock:
            sock.sendall(struct.pack(">I", len(payload)) + payload)
            with sock.makefile("rb") as stream:
                header = stream.read(4)
                if len(header) != 4:
                    raise ConnectionError("Editor closed before sending a response header")
                size = struct.unpack(">I", header)[0]
                body = stream.read(size)
                if len(body) != size:
                    raise ConnectionError("Editor returned an incomplete response")
                reply = json.loads(body)
        break
    except OSError as exc:
        if attempt == 4:
            raise SystemExit(f"Could not read the editor listener: {exc}") from exc
        time.sleep(0.1)

if not reply.get("ok"):
    raise SystemExit(f"Editor did not complete the command: {reply}")
data = reply.get("data")
if not isinstance(data, str):
    raise SystemExit(f"Expected a text result, received: {data}")
print(data.rstrip("\n"))
