#!/usr/bin/env python3
"""
UE Wingman command-line tool.  This tool simply packages up its
argv and sends it to the plugin, and then prints whatever the
plugin sends back.  All the real work is done in the plugin.

Usage: ue-wingman.py <arg1> [arg2 ...]
"""

import sys
import socket
import struct

HOST = "localhost"
PORT = 9851
TIMEOUT = 15


def main():
    args = sys.argv[1:]

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.settimeout(TIMEOUT)
    try:
        sock.connect((HOST, PORT))
    except (ConnectionRefusedError, socket.timeout, OSError) as e:
        print(f"Cannot connect to {HOST}:{PORT} — is the editor running?")
        sys.exit(1)

    payload = bytearray()
    for arg in args:
        data = arg.encode()
        payload += struct.pack("!I", len(data))
        payload += data
    sock.sendall(struct.pack("!I", len(payload)))
    sock.sendall(payload)
    sock.shutdown(socket.SHUT_WR)

    result = b""
    while True:
        chunk = sock.recv(65536)
        if not chunk:
            break
        result += chunk

    sock.close()
    print(result.decode(), end="")

if __name__ == "__main__":
    main()
