import socket, threading

class TCIA_Network:
    def __init__(self, port=5000):
        self.port = port
        self.connections = []

    def start_server(self, callback):
        server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server.bind(("0.0.0.0", self.port))
        server.listen()

        def handle_client(conn, addr):
            data = conn.recv(4096).decode()
            response = callback(data)
            conn.send(response.encode())
            conn.close()

        def listen():
            while True:
                conn, addr = server.accept()
                self.connections.append(addr)
                threading.Thread(target=handle_client, args=(conn, addr)).start()

        threading.Thread(target=listen, daemon=True).start()

    def send_to(self, host, message):
        try:
            client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            client.connect((host, self.port))
            client.send(message.encode())
            response = client.recv(4096).decode()
            client.close()
            return response
        except Exception as e:
            return f"Falha ao enviar: {e}"