import webbrowser
from threading import Timer
from flask import Flask, render_template_string, redirect
import socket

app = Flask(__name__)

def check_internet(host="8.8.8.8", port=53, timeout=2):
    try:
        socket.setdefaulttimeout(timeout)
        socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((host, port))
        return True
    except Exception:
        return False

@app.route('/')
def index():
    url = "https://saumyadip-kar.github.io/LEO-Satellite-Simulator/"
    if check_internet():
        return redirect(url)
    else:
        error_html = '''
        <!DOCTYPE html>
        <html>
        <head>
            <title>Network Error</title>
            <meta charset="utf-8">
            <style>
                body { background: #28527a; color: #fff; font-family: Segoe UI, sans-serif; text-align: center; padding-top: 60px; }
                .err { font-size: 2em; font-weight: bold; }
                .desc { font-size: 1.2em; margin-top: 18px; }
            </style>
            <script>
                const url = "{{ target_url }}";
                async function checkOnlineAndRedirect() {
                    try {
                        const online = window.navigator.onLine;
                        if (online) {
                            window.location.href = url;
                        }
                    } catch(e) {}
                }
                setInterval(checkOnlineAndRedirect, 2000);
            </script>
        </head>
        <body>
            <div class="err">-- CHECK YOUR NETWORK --</div>
            <div class="desc">Internet connection not detected.<br>This simulator needs a stable internet connection to work properly.</div>
        </body>
        </html>
        '''
        return render_template_string(error_html, target_url=url)

def open_browser():
    webbrowser.open("http://127.0.0.1:8888")

if __name__ == "__main__":
    # Open browser after Flask starts
    Timer(1, open_browser).start()
    app.run(port=8888, debug=False)
