#!/usr/bin/env python3
"""Serve the bundled application locally using only the Python standard library."""
import argparse
from functools import partial
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
import webbrowser


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--port', type=int, default=0, help='local port; default chooses a free port')
    parser.add_argument('--no-browser', action='store_true', help='print the URL without opening a browser')
    args = parser.parse_args()
    if not 0 <= args.port <= 65535:
        parser.error('--port must be between 0 and 65535')
    site = Path(__file__).resolve().parent / 'site'
    if not (site / 'index.html').is_file():
        parser.error('site/index.html is missing; extract the complete ready-to-run archive')

    class Handler(SimpleHTTPRequestHandler):
        extensions_map = {**SimpleHTTPRequestHandler.extensions_map,
                          '.js': 'text/javascript', '.mjs': 'text/javascript',
                          '.css': 'text/css', '.json': 'application/json',
                          '.wasm': 'application/wasm', '.glb': 'model/gltf-binary'}

        def end_headers(self):
            self.send_header('Cache-Control', 'no-cache')
            super().end_headers()

    try:
        server = ThreadingHTTPServer(('127.0.0.1', args.port), partial(Handler, directory=str(site)))
    except OSError as error:
        parser.error(f'Cannot start the local server: {error}. Try another --port.')
    with server:
        url = f'http://127.0.0.1:{server.server_port}/'
        print(f'Open {url} (Ctrl+C stops the server)', flush=True)
        if not args.no_browser:
            webbrowser.open(url)
        try:
            server.serve_forever()
        except KeyboardInterrupt:
            pass


if __name__ == '__main__':
    main()
