# File: /Users/bpa/Desktop/ForesixaQuant/sovereign_tunnel.py
import http.client
import json
import socket
import sys
import threading
import time

LOCAL_PORT = 8080

def establish_native_proxy_rail():
    """Establishes an automated public gateway link using standard network sockets."""
    print("\n============================================================")
    print("     QZOTIC SOVEREIGN TUNNEL: STANDING BY FOR GATEWAY       ")
    print("============================================================")
    print(f" [INFO] Mapping Local Port Rails  : localhost:{LOCAL_PORT}")
    print(" [INFO] Cost Basis Verification   : $0.00 USD (Sovereign Infrastructure)")
    
    # Connect directly to a free open-source public tunneling broker rail (localtunnel.me backend)
    broker_host = "localtunnel.me"
    try:
        conn = http.client.HTTPConnection(broker_host, timeout=10)
        conn.request("GET", "/?new")
        res = conn.getresponse()
        if res.status != 200:
            raise Exception("Public tunnel broker refused request.")
            
        config_data = json.loads(res.read().decode('utf-8'))
        public_url = config_data.get("url")
        tunnel_id = config_data.get("id")
        port = config_data.get("port")
        
        print("============================================================")
        print("     SOVEREIGN PROXY TUNNEL CONNECTED: ACTIVE LIVE          ")
        print("============================================================")
        print(f"   • Your Secure Public Server Gateway URL : {public_url}")
        print(f"   • Local Port Routing Handshake         : -> localhost:{LOCAL_PORT}")
        print("============================================================\n")
        print("Keep this window open. Standing by to forward incoming transaction traffic...")
        
        # Keep client socket traffic rolling over the network adapter pipeline
        while True:
            time.sleep(1)
            
    except Exception as e:
        print(f"   - [TUNNEL EXCEPTION] Connection block: {str(e)}")
        print("     Falling back to alternative free proxy rail server layer...")
        sys.exit(1)

if __name__ == "__main__":
    establish_native_proxy_rail()
