"""cambc map-editor — open map editor locally or on platform."""

import click
from rich.console import Console

console = Console()


@click.command("map-editor")
@click.option("--platform", "use_platform", is_flag=True, help="Open map editor on platform instead of locally")
def map_editor(use_platform: bool):
    """Open the map editor.

    \b
    Examples:
      cambc map-editor              # Open map editor locally
      cambc map-editor --platform   # Open on platform
    """
    if use_platform:
        _open_platform()
    else:
        _serve_local()


def _open_platform() -> None:
    """Open the platform map editor page in the user's browser."""
    import webbrowser
    from cambc.auth import get_api_url

    base_url = get_api_url()
    url = f"{base_url}/map-editor"

    console.print(f"Opening map editor: [link={url}]{url}[/link]")
    webbrowser.open(url)


def _serve_local() -> None:
    """Serve the map editor locally."""
    import http.server
    import threading
    import webbrowser
    from pathlib import Path

    mono_dist = Path(__file__).parent.parent.parent.parent.parent / "visualiser" / "dist"
    bundled_dist = Path(__file__).parent.parent / "data" / "visualiser"

    if (mono_dist / "map-editor.html").is_file():
        dist_path = mono_dist.resolve()
    elif (bundled_dist / "map-editor.html").is_file():
        dist_path = bundled_dist.resolve()
    else:
        console.print(
            "[red]Map editor not found. "
            "Try reinstalling cambc or use --platform to open on the platform.[/red]"
        )
        if mono_dist.exists():
            console.print(
                f"[dim]Found {mono_dist} but it has no map-editor.html — "
                "try building the visualiser: cd visualiser && bun run build[/dim]"
            )
        raise SystemExit(1)

    from cambc.auth import get_api_url
    cdn_base = get_api_url() + "/assets/vis/"

    class EditorHandler(http.server.SimpleHTTPRequestHandler):
        def __init__(self, *args, **kwargs):
            super().__init__(*args, directory=str(dist_path), **kwargs)

        def do_GET(self):
            # Serve map-editor.html for root path
            if self.path == "/" or self.path.startswith("/?"):
                self.path = "/map-editor.html"
            # Proxy texture requests to CDN
            if self.path.startswith("/vis/"):
                self._proxy_cdn(self.path[5:])
                return
            super().do_GET()

        def _proxy_cdn(self, asset_path: str):
            import urllib.request
            import urllib.error
            try:
                url = cdn_base + asset_path
                with urllib.request.urlopen(url, timeout=10) as resp:
                    data = resp.read()
                    self.send_response(200)
                    ct = resp.headers.get("Content-Type", "application/octet-stream")
                    self.send_header("Content-Type", ct)
                    self.send_header("Content-Length", str(len(data)))
                    self.send_header("Cache-Control", "public, max-age=86400")
                    self.end_headers()
                    self.wfile.write(data)
            except urllib.error.HTTPError as e:
                self.send_error(e.code)
            except Exception:
                self.send_error(502, "Failed to fetch asset from CDN")

        def log_message(self, format, *args):
            pass

    server = http.server.HTTPServer(("127.0.0.1", 0), EditorHandler)
    port = server.server_address[1]

    url = f"http://127.0.0.1:{port}/?assetBaseUrl=/vis/"
    console.print(f"Serving map editor at [link={url}]{url}[/link]")
    console.print("[dim]Press Ctrl+C to stop[/dim]")

    threading.Timer(0.5, lambda: webbrowser.open(url)).start()

    try:
        server.serve_forever()
    except KeyboardInterrupt:
        console.print("\n[dim]Stopped.[/dim]")
        server.shutdown()
