import io
import sys

import click

from geo.core.query import parse_bbox


def _ensure_utf8_stdout():
    """Reconfigure stdout for UTF-8 on Windows (braille chars need it)."""
    if sys.platform == "win32" and hasattr(sys.stdout, "reconfigure"):
        sys.stdout.reconfigure(encoding="utf-8")


@click.command()
@click.argument("file", type=click.Path(exists=True))
@click.option("--bbox", default=None, help="Initial bounding box: west,south,east,north")
@click.option("--static", is_flag=True, help="Static render (no interactive controls)")
@click.pass_context
def view(ctx, file, bbox, static):
    """Render a dataset as a braille map in the terminal.

    Interactive mode: +/- to zoom, arrows to pan, q to quit.
    Use --static for a single non-interactive render (pipe-friendly).
    """
    _ensure_utf8_stdout()
    parsed_bbox = parse_bbox(bbox) if bbox else None

    if static or not sys.stdout.isatty():
        from geo.render.display import render_static
        click.echo(render_static(file, bbox=parsed_bbox))
    else:
        from geo.render.display import render_interactive
        render_interactive(file, bbox=parsed_bbox)
