import webbrowser
from http.server import HTTPServer

import click

from geo.server.handler import make_handler


def run_server(dataset_path: str, port: int = 8080, open_browser: bool = True):
    """Start a local HTTP server serving a dataset on a Leaflet map."""
    handler_class = make_handler(dataset_path)
    server = HTTPServer(("localhost", port), handler_class)
    url = f"http://localhost:{port}"
    click.echo(f"Serving {dataset_path} at {url}", err=True)
    click.echo("Press Ctrl+C to stop.", err=True)

    if open_browser:
        webbrowser.open(url)

    try:
        server.serve_forever()
    except KeyboardInterrupt:
        click.echo("\nShutting down.", err=True)
        server.shutdown()
