import socket
import time
import sys

# --- CONFIGURATION ---
VPS_IP = "165.1.125.122"
VPS_PORT = 57373
LOCAL_PORT = 57373
HEARTBEAT_INTERVAL = 30  # Seconds
# --- --- --- --- ---

print("--- CCJ Host Bridge ---")
print(f"Connecting to VPS {VPS_IP}:{VPS_PORT}...")

def punch():
    """ 
    Sends a packet to the VPS to register as the Host.
    We try to use the same port the game uses (57373).
    """
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    
    # Allow other processes (like the game) to use the same port if possible
    try:
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        if sys.platform != "win32":
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
    except:
        pass

    try:
        sock.bind(("0.0.0.0", LOCAL_PORT))
        print(f"[+] Bound to local port {LOCAL_PORT}")
    except Exception as e:
        print(f"[!] Could not bind to port {LOCAL_PORT}: {e}")
        print("[!] Trying with an ephemeral port... (Warning: Client might not find you!)")
        # If we can't bind to 57373, the game is probably already running.
        # We can still send the hello, but the CGNAT mapping might be different.

    print(f"[*] Sending registration to {VPS_IP}:{VPS_PORT}...")
    
    while True:
        try:
            # Send the signature that the Relay expects to identify the Host
            sock.sendto(b"HOST_HELLO", (VPS_IP, VPS_PORT))
            print(f"[^] Heartbeat sent at {time.strftime('%H:%M:%S')}")
            time.sleep(HEARTBEAT_INTERVAL)
        except KeyboardInterrupt:
            print("\nStopping bridge...")
            break
        except Exception as e:
            print(f"[!] Error: {e}")
            time.sleep(5)

if __name__ == "__main__":
    punch()
