import socket
import threading
import time

HOST = "0.0.0.0"
PORT = 12345
FRAME_SIZE = 1000
FRAME_DELAY = 0.02

clients = []

def handle_client(client_sock, client_id):
    print(f"Starting handle_client for Client {client_id}")
    while True:
        try:
            other_client = clients[1 - client_id] if len(clients) == 2 else None
            print(f"Client {client_id} waiting for data, other_client exists: {other_client is not None}")
            data = client_sock.recv(1024)
            if not data:
                print(f"Client {client_id} disconnected or no data received")
                break
            if other_client:
                for i in range(0, len(data), FRAME_SIZE):
                    frame = data[i:i + FRAME_SIZE]
                    other_client.send(frame)
                    time.sleep(FRAME_DELAY)
                print(f"Forwarded {len(data)} bytes from Client {client_id} to Client {1 - client_id}")
        except Exception as e:
            print(f"Error with Client {client_id}: {e}")
            break
    print(f"Closing connection for Client {client_id}")
    client_sock.close()

def start_simulator():
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.bind((HOST, PORT))
    server.listen(2)
    print(f"GSM Simulator listening on {HOST}:{PORT}...")

    while len(clients) < 2:
        client_sock, addr = server.accept()
        client_sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)  # Keep connection alive
        clients.append(client_sock)
        client_id = len(clients) - 1
        print(f"Client {client_id} connected from {addr}")
        threading.Thread(target=handle_client, args=(client_sock, client_id), daemon=True).start()

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        print("Shutting down simulator...")
        for client in clients:
            client.close()
        server.close()

if __name__ == "__main__":
    start_simulator()