#!/usr/bin/env python3
"""Serves this exported folder over http://127.0.0.1 so camera-based
features (hand-tracking steering, theremin) work. Browsers block camera
access entirely when index.html is opened directly (file://) — this is a
browser security rule, not a bug in the export — but treat 127.0.0.1 as a
secure origin exactly like the live site. Requires only Python 3."""
import http.server
import os
import socket
import threading
import webbrowser

os.chdir(os.path.dirname(os.path.abspath(__file__)))


def find_free_port():
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.bind(("127.0.0.1", 0))
        return s.getsockname()[1]


port = find_free_port()
url = "http://127.0.0.1:{}/index.html".format(port)
httpd = http.server.ThreadingHTTPServer(("127.0.0.1", port), http.server.SimpleHTTPRequestHandler)

print("Serving this piece at " + url)
print("Camera-based steering now works here (it cannot work when opening index.html directly).")
print("Press Ctrl+C to stop.")

threading.Timer(0.6, lambda: webbrowser.open(url)).start()
try:
    httpd.serve_forever()
except KeyboardInterrupt:
    pass