"""
OmniAnti launcher — called when user runs 'omnianti' in terminal
"""
import os
import sys
import threading
import time
import webbrowser
from http.server import HTTPServer


def main():
    # Find the templates folder inside the installed package
    pkg_dir = os.path.dirname(os.path.abspath(__file__))

    # Add package dir to path so app.py can find templates
    sys.path.insert(0, pkg_dir)
    os.chdir(pkg_dir)

    PORT = 5000

    print("""
╔══════════════════════════════════════════════════╗
║   OMNIANTI — Windows 11 Edition                  ║
║   Advanced Real System Scanner v2.0              ║
╠══════════════════════════════════════════════════╣
║   Server : http://localhost:5000                 ║
║   Press Ctrl+C to stop                          ║
╚══════════════════════════════════════════════════╝
    """)

    # Open browser after 2 seconds
    def open_browser():
        time.sleep(2)
        webbrowser.open(f"http://localhost:{PORT}")

    threading.Thread(target=open_browser, daemon=True).start()

    # Import and run the app server
    import importlib.util
    spec = importlib.util.spec_from_file_location("app", os.path.join(pkg_dir, "app.py"))
    app_module = importlib.util.load_from_spec(spec)
    spec.loader.exec_module(app_module)

    server = HTTPServer(("localhost", PORT), app_module.OmniAntiHandler)
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        print("\n[OmniAnti] Server stopped.")
        server.server_close()


if __name__ == "__main__":
    main()
