"""Map / Geo visualization generation.""" from __future__ import annotations from typing import Any import duckdb from visual_notebook.viz._common import PALETTE def compute_map( con: duckdb.DuckDBPyConnection, table_name: str, lat_col: str, lon_col: str, label_col: str | None = None, max_points: int = 5000, ) -> dict[str, Any]: """Compute map data and return Leaflet-friendly spec.""" count = con.execute(f'SELECT COUNT(*) FROM "{table_name}"').fetchone()[0] sample_clause = f"USING SAMPLE {max_points}" if count > max_points else "" cols = f'"{lat_col}", "{lon_col}"' if label_col: cols += f', "{label_col}"' result = con.execute(f'SELECT {cols} FROM "{table_name}" {sample_clause} WHERE "{lat_col}" IS NOT NULL AND "{lon_col}" IS NOT NULL').fetchall() points = [] for row in result: point = {"lat": float(row[0]), "lon": float(row[1])} if label_col: point["label"] = str(row[2]) points.append(point) if points: lats = [p["lat"] for p in points] lons = [p["lon"] for p in points] bounds = { "minLat": min(lats), "maxLat": max(lats), "minLon": min(lons), "maxLon": max(lons), } center = { "lat": (bounds["minLat"] + bounds["maxLat"]) / 2, "lon": (bounds["minLon"] + bounds["maxLon"]) / 2, } else: bounds = {"minLat": 0, "maxLat": 0, "minLon": 0, "maxLon": 0} center = {"lat": 0, "lon": 0} return { "type": "map", "points": points, "bounds": bounds, "center": center, "pointCount": len(points), }