
import socket, time, threading
import sys, os, json
from   sentence_transformers import SentenceTransformer
from   PIL import Image


def sendMsg( sock, msg ):
    try:
        utf8 = msg.encode('utf-8')
    
        mlen = len(utf8);
        hdr = str(mlen).zfill(16)
        hdr_utf8 = hdr.encode('utf-8')
        #print("hdr_utf8 len=", len(hdr_utf8))
    
        #print("send hdr .. ", hdr_utf8, flush=True )
        sock.sendall( hdr_utf8 );
        #print("send hdr done ", hdr_utf8, flush=True )
    
        #print("send utf8 ... ", utf8, flush=True )
        sock.sendall( utf8 )
        #print("send utf8 done ", utf8, flush=True )
        ##client_socket.send(result.encode('utf-8'))

    except:
        pass


def recvMsg( sock ):
    try:
        hdr = sock.recv(16);
        if not hdr:
            return None

        hdr_utf8 = hdr.decode('utf-8')
    
        mlen = int(hdr_utf8)
        #print("mlen=", mlen, flush=True)

        #print(f"receiving {mlen} ...", flush=True)
        cmd = sock.recv(mlen).decode('utf-8')
        if not cmd:
            return None

        #print(f"receiving done {cmd}", flush=True)
        #print(cmd, flush=True )
        return cmd

    except:
        #print("recvMsg exception", flush=True)
        return ''


def handle_client(client_socket):
    while True:
        #data = client_socket.recv(1024)
        command = recvMsg( client_socket )
        if not command:
            break

        #message = data.decode('utf-8')
        if command == 'QUIT':
            break

        #print(f"Received message: {command}")
        exec_result = {}

        try:
            exec(command, {}, exec_result)
            result = exec_result.get("JAG_RESULT", "0")
        except:
            result = "0"

        #response = "Server received your message: " + command + ' ' + result
        sendMsg( client_socket, result )
        ##client_socket.sendall(response.encode('utf-8'))

    #print("client socket close")
    client_socket.close()


### setup some models


def main():
    # Define the server socket using Unix domain socket
    server_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    server_socket.setblocking(True)
    
    # Specify the socket file path
    socket_file = '/tmp/pyai_server_socket'
    #print(f"Server is openning {socket_file}", flush=True)
    
    # Bind the server socket to the socket file
    server_socket.bind(socket_file)
    os.chmod( socket_file, 0o777)
    
    #server_socket.setsockopt(socket.SOL_SOCKET, socket.TCP_NODELAY, 1)
    
    # Listen for incoming connections
    server_socket.listen(100)
    #print(f"Server is listening on {socket_file}", flush=True)
    
    #server_socket.setsockopt(socket.SOL_SOCKET, socket.TCP_NODELAY, 1)

    while True:
        client_socket, client_address = server_socket.accept()
        #print(f"Accepted connection from {client_address}")
        client_handler = threading.Thread(target=handle_client, args=(client_socket,))
        client_handler.start()
    
    

if __name__ == "__main__":
    main()
    
