import socket
import struct

class MCRcon:
    def __init__(self, host, password, port=25575, timeout=3):
        self.host = host
        self.password = password
        self.port = port
        self.timeout = timeout
        self.sock = None

    def connect(self):
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.settimeout(self.timeout)
        self.sock.connect((self.host, self.port))
        # Auth packet: id=1, type=3 (auth), body=password
        self._send(1, 3, self.password)
        resp_id, resp_type, resp_body = self._read()
        if resp_id == -1 or resp_type != 2:
            raise ConnectionError("RCON authentication failed")

    def command(self, cmd):
        if not self.sock:
            self.connect()
        try:
            self._send(2, 2, cmd)
            resp_id, resp_type, resp_body = self._read()
            return resp_body
        except Exception:
            self.close()
            raise

    def close(self):
        if self.sock:
            try:
                self.sock.close()
            except Exception:
                pass
            self.sock = None

    def _send(self, req_id, req_type, body):
        body_bytes = body.encode("utf-8") + b"\x00\x00"
        length = len(body_bytes) + 8
        packet = struct.pack("<iii", length, req_id, req_type) + body_bytes
        self.sock.sendall(packet)

    def _read(self):
        data = self.sock.recv(4)
        if not data or len(data) < 4:
            return -1, -1, ""
        length = struct.unpack("<i", data)[0]
        payload = b""
        while len(payload) < length:
            chunk = self.sock.recv(min(length - len(payload), 4096))
            if not chunk:
                break
            payload += chunk
        req_id, req_type = struct.unpack("<ii", payload[:8])
        body = payload[8:-2].decode("utf-8", errors="replace")
        return req_id, req_type, body
