#!/usr/bin/env python3

import socket
HOST = "euclid.nmu.edu"  # change if needed
PORT = 4242

def recv_exact(sock, n):
    """Receive exactly n bytes"""
    data = b""
    while len(data) < n:
        chunk = sock.recv(n - len(data))
        if not chunk:
            raise ConnectionError("Connection closed prematurely")
        data += chunk
    return data

def main():
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.connect((HOST, PORT))
        print(f"[*] Connected to {HOST}:{PORT}")

        while True:
            # 1) Read user input
            message = input("> ").encode()

            # 2) Prepend 3-digit length
            length = len(message)
            prefix = f"{length:03d}".encode()
            to_send = prefix + message

            # 3) Send to server
            s.sendall(to_send)


            # 4) Read 3-byte length prefix from server
            raw_len = recv_exact(s, 3)
            try:
                reply_len = int(raw_len.decode())
            except ValueError:
                print("[!] Invalid length prefix from server")
                break

            # 5) Read the rest of the message
            payload = recv_exact(s, reply_len)

            # 6) Verify length
            if len(payload) != reply_len:
                print(f"[!] Length mismatch: prefix said {reply_len}, actual {len(payload)}")
                break

            # 7) Print the server reply
            print(payload.decode(errors="ignore"))

if __name__ == "__main__":
    main()
