#!/usr/bin/env python3
"""
Multiple Tunnels Example - Run multiple tunnels simultaneously
"""

from suxitunnel import Tunnel
import http.server
import socketserver
import threading
from functools import partial

def create_handler(message):
    """Create a custom request handler that returns a specific message"""
    class CustomHandler(http.server.SimpleHTTPRequestHandler):
        def do_GET(self):
            self.send_response(200)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            response = f"""
            <html>
                <head><title>{message}</title></head>
                <body>
                    <h1>{message}</h1>
                    <p>This is a separate tunnel!</p>
                </body>
            </html>
            """
            self.wfile.write(response.encode())
        
        def log_message(self, format, *args):
            # Suppress logs
            pass
    
    return CustomHandler

def start_server(port, handler):
    """Start an HTTP server on a specific port"""
    with socketserver.TCPServer(("", port), handler) as httpd:
        httpd.serve_forever()

if __name__ == "__main__":
    # Define services
    services = [
        {"port": 8000, "name": "Service A - Frontend"},
        {"port": 8001, "name": "Service B - API"},
        {"port": 8002, "name": "Service C - Admin"},
    ]
    
    tunnels = []
    
    try:
        # Start servers and tunnels
        print("Starting multiple services with tunnels...\n")
        
        for service in services:
            port = service["port"]
            name = service["name"]
            
            # Start server
            handler = create_handler(name)
            thread = threading.Thread(
                target=start_server,
                args=(port, handler),
                daemon=True
            )
            thread.start()
            
            # Create tunnel
            print(f"Creating tunnel for {name}...")
            tunnel = Tunnel(port)
            tunnels.append({"tunnel": tunnel, "name": name})
            
        print(f"\n{'='*60}")
        print("✅ All tunnels are live!")
        print(f"{'='*60}")
        
        for item in tunnels:
            print(f"\n{item['name']}:")
            print(f"  Local:  http://localhost:{item['tunnel'].port}")
            print(f"  Public: {item['tunnel'].url}")
        
        print(f"\n{'='*60}")
        print("All services are publicly accessible!")
        print("Press Ctrl+C to close all tunnels...")
        print(f"{'='*60}\n")
        
        # Keep running
        try:
            while True:
                # Check if tunnels are still alive
                alive = sum(1 for item in tunnels if item['tunnel'].is_alive())
                if alive < len(tunnels):
                    print(f"\n⚠️  Warning: {len(tunnels) - alive} tunnel(s) disconnected")
                
                import time
                time.sleep(5)
        except KeyboardInterrupt:
            print("\n\nClosing all tunnels...")
    
    finally:
        # Close all tunnels
        for item in tunnels:
            item['tunnel'].close()
        print("✅ All tunnels closed.")
