Source code for cng_datasets.vector.convert_to_parquet

#!/usr/bin/env python3
"""
Convert vector datasets to optimized GeoParquet format.

Simple workflow:
1. Detect source CRS using GDAL
2. Read data with DuckDB ST_Read
3. Add ID column if needed
4. Reproject if needed (ST_Transform + ST_FlipCoordinates)
5. Write GeoParquet 1.1 with DuckDB COPY, plus a bbox covering column (#340)
6. Upload to S3 via rclone if needed
"""

import argparse
import functools
import sys
import tempfile
import os
import shutil
import subprocess
import zipfile
import re
import json
from typing import NamedTuple, Optional, Tuple, List, Union
import duckdb
import geopandas as gpd
from urllib.request import urlretrieve
from urllib.parse import urlparse
from ..duckdb_memory import to_duckdb_memory_limit
from ..provenance import kv_metadata_sql
from .geoparquet import GEOPARQUET_VERSION, covering_columns, plan_covering


# Curved geometry types that DuckDB's WKB parser cannot handle
_CURVED_GEOMETRY_TYPES = frozenset({
    'multisurface', 'curvepolygon', 'compoundcurve',
    'circularstring', 'multicurve',
})

# Substrings that indicate M or Z coordinates in an ogrinfo geometry-type line.
# DuckDB's spatial extension stores these as BLOB rather than GEOMETRY, which
# breaks reprojection, bbox computation, hex aggregation, and PMTiles export.
# Flattening to 2D with ogr2ogr before ST_Read avoids the BLOB issue entirely.
_NON_2D_GEOMETRY_PATTERNS = ('3d ', 'measured', ' z', ' m', 'z,', 'm,')

# Upper bound on the (uncompressed) size of a single Parquet row group, passed to
# DuckDB's COPY as ROW_GROUP_SIZE_BYTES. This caps the per-column chunk size so
# the geometry column never produces one giant chunk.
#
# Why this exists (issue #106): DuckDB's httpfs reader aborts with a bare
# "Error: stoi" when it has to read a single Parquet column chunk larger than
# ~2.85 GB — even though a local read of the exact same file decodes fine. The
# row-count limit (ROW_GROUP_SIZE) can't prevent this because bytes-per-feature
# varies enormously (full-precision FEMA/IUCN multipolygons run tens of KB each),
# so the default 100k rows packs into one ~2.9 GB chunk that is unreadable over
# S3/httpfs by the duckdb-mcp server. A 1 GB byte budget keeps chunks an order of
# magnitude under the cliff regardless of geometry size. Verified against the
# issue's MRE: the byte-capped file full-scans cleanly on the MCP.
DEFAULT_ROW_GROUP_BYTES = "1GB"


def _is_gdb_source(source_url: str) -> bool:
    """Check if source is a GDAL FileGDB or OpenFileGDB source."""
    # Strip VSI prefixes to check file extension
    cleaned = source_url.lower()
    for prefix in ('/vsicurl/', '/vsis3/', '/vsigzip/'):
        cleaned = cleaned.replace(prefix, '')
    return cleaned.rstrip('/').endswith('.gdb')



def _has_non_2d_geometry(source_url: str, layer: Optional[str] = None) -> bool:
    """
    Return True if the source contains measured (M) or 3D (Z) geometry.

    DuckDB's spatial extension reads M/Z geometry as BLOB rather than GEOMETRY,
    which silently breaks downstream reprojection, bbox stats, hex aggregation,
    and PMTiles export.  Detecting this upfront lets us route the source through
    ogr2ogr -dim XY before passing it to DuckDB.
    """
    cmd = ['ogrinfo', '-al', '-so', source_url]
    if layer:
        cmd.append(layer)
    try:
        result = subprocess.run(cmd, capture_output=True, text=True, timeout=60)
        for line in result.stdout.splitlines():
            if line.strip().startswith('Geometry:'):
                geom_type = line.split(':', 1)[1].strip().lower()
                if any(pat in geom_type for pat in _NON_2D_GEOMETRY_PATTERNS):
                    return True
    except Exception:
        pass
    return False


def _flatten_to_2d(source_inputs: Union[str, List[str]], layer: Optional[str] = None,
                   verbose: bool = False) -> Tuple[str, Optional[str], Optional[str]]:
    """
    Flatten measured/3D geometries to strictly 2D using ``ogr2ogr -dim XY``.

    All inputs (single file or list) are merged into one temp GPKG so that the
    rest of the pipeline always sees a single, DuckDB-readable source with a
    proper GEOMETRY column instead of BLOB.

    Returns:
        (new_source_path, new_layer, temp_dir_to_cleanup)
        On failure returns (source_inputs, layer, None) and prints a warning.
    """
    print("  Non-2D geometry detected — flattening to 2D with ogr2ogr (-dim XY)...")

    flat_dir = tempfile.mkdtemp(prefix='cng_flatten_')
    output_path = os.path.join(flat_dir, 'flattened.gpkg')

    sources = [source_inputs] if isinstance(source_inputs, str) else list(source_inputs)

    try:
        for i, src in enumerate(sources):
            ogr_cmd = ['ogr2ogr', '-f', 'GPKG', '-dim', 'XY']
            if i > 0:
                ogr_cmd.append('-append')
            ogr_cmd += [output_path, src]
            if layer:
                ogr_cmd.append(layer)
            subprocess.run(ogr_cmd, check=True, capture_output=True, text=True, timeout=7200)

        if verbose:
            print(f"  Flattened to temp GPKG: {output_path}")
        return output_path, None, flat_dir

    except subprocess.CalledProcessError as e:
        print(f"  Warning: ogr2ogr flatten to 2D failed: {e.stderr}")
        print("  Proceeding with original source (may produce BLOB geometry column)")
        shutil.rmtree(flat_dir, ignore_errors=True)
        return source_inputs, layer, None


def _linearize_source(source_url: str, layer: Optional[str] = None,
                      verbose: bool = False) -> Tuple[str, Optional[str], Optional[str]]:
    """
    Pre-process a vector source through ogr2ogr to linearize curved
    geometries and promote to multi-type.  This is always applied to
    GDB sources because the layer metadata can report "Multi Polygon"
    while individual features silently contain MULTISURFACE WKB types
    that DuckDB cannot parse.

    For already-linear geometries the ogr2ogr flags are a no-op, so this
    is safe to apply unconditionally.

    Returns:
        (new_source, new_layer, temp_dir_to_cleanup)
        If linearization is skipped: (source_url, layer, None)
    """
    if not _is_gdb_source(source_url):
        if verbose:
            print("  Source is not a GDB — skipping linearization")
        return source_url, layer, None

    print("  GDB source detected — linearizing with ogr2ogr "
          "(CONVERT_TO_LINEAR + PROMOTE_TO_MULTI)...")

    lin_dir = tempfile.mkdtemp(prefix='cng_linearize_')
    output_path = os.path.join(lin_dir, 'linearized.gpkg')

    ogr_cmd = [
        'ogr2ogr', '-f', 'GPKG',
        '-nlt', 'CONVERT_TO_LINEAR',
        '-nlt', 'PROMOTE_TO_MULTI',
        output_path, source_url,
    ]
    if layer:
        ogr_cmd.append(layer)

    try:
        subprocess.run(ogr_cmd, check=True, capture_output=True, text=True, timeout=7200)
        print(f"  Linearized to temp GPKG: {output_path}")
        return output_path, None, lin_dir
    except subprocess.TimeoutExpired:
        print("  Warning: ogr2ogr linearization timed out, proceeding with original source")
        shutil.rmtree(lin_dir, ignore_errors=True)
        return source_url, layer, None
    except subprocess.CalledProcessError as e:
        print(f"  Warning: ogr2ogr linearization failed: {e.stderr}")
        print("  Proceeding with original source (may fail on curved geometries)")
        shutil.rmtree(lin_dir, ignore_errors=True)
        return source_url, layer, None


def is_parquet_file(source_url: str) -> bool:
    """
    Check if a source URL points to a parquet file.

    Args:
        source_url: Source dataset URL

    Returns:
        True if the file ends with .parquet, False otherwise
    """
    # Parse URL to get the path component
    parsed = urlparse(source_url)
    path = parsed.path if parsed.path else source_url
    return path.lower().endswith('.parquet')


def is_csv_file(source_url: str) -> bool:
    """
    Check if a source URL points to a CSV/TSV file.

    CSV point datasets (lat/lon columns) are a common distribution format for
    point observations (species occurrences, sensor stations, vent locations)
    and are handled by a dedicated read_csv + ST_Point path (issue #78).

    Args:
        source_url: Source dataset URL

    Returns:
        True if the file ends with .csv/.tsv, False otherwise
    """
    parsed = urlparse(source_url)
    path = parsed.path if parsed.path else source_url
    return path.lower().endswith(('.csv', '.tsv'))


# Case-insensitive candidate names for latitude/longitude columns in a CSV,
# in priority order. Used when --lat-column/--lon-column are not given (#78).
_LAT_COLUMN_CANDIDATES = ('latitude', 'lat', 'y', 'ycoord', 'y_coord', 'decimallatitude')
_LON_COLUMN_CANDIDATES = ('longitude', 'lon', 'lng', 'long', 'x', 'xcoord', 'x_coord', 'decimallongitude')


def _resolve_latlon_columns(
    column_names: List[str],
    lat_column: Optional[str] = None,
    lon_column: Optional[str] = None,
) -> Tuple[str, str]:
    """Resolve the latitude and longitude column names for a CSV point source.

    Uses the explicit ``lat_column``/``lon_column`` when given (case-insensitive
    match), otherwise auto-detects from common names (issue #78). Returns the
    actual column names as they appear in the source (preserving case).

    Raises:
        ValueError: a specified column is absent, or auto-detection finds no
            latitude/longitude column.
    """
    lower_map = {c.lower(): c for c in column_names}

    def _resolve(specified, candidates, axis):
        if specified:
            actual = lower_map.get(specified.lower())
            if actual is None:
                raise ValueError(
                    f"Specified {axis} column '{specified}' not found in CSV. "
                    f"Available columns: {', '.join(column_names)}"
                )
            return actual
        for cand in candidates:
            if cand in lower_map:
                return lower_map[cand]
        raise ValueError(
            f"Could not auto-detect a {axis} column in the CSV "
            f"(looked for {', '.join(candidates)}). "
            f"Specify it explicitly with --{axis[:3]}-column. "
            f"Available columns: {', '.join(column_names)}"
        )

    return (
        _resolve(lat_column, _LAT_COLUMN_CANDIDATES, 'latitude'),
        _resolve(lon_column, _LON_COLUMN_CANDIDATES, 'longitude'),
    )


def to_gdal_readable(url: str) -> str:
    """
    Rewrite a remote source URL into a GDAL /vsicurl path so ST_Read can open it.

    GDAL cannot open a bare ``s3://`` path without /vsis3 credentials configured,
    and this tool does not set them (issue #153). The NRP object store is reachable
    over plain HTTPS, so ``s3://bucket/key`` is rewritten to its public HTTPS
    endpoint and then streamed via /vsicurl. Plain ``http(s)://`` URLs are wrapped
    in /vsicurl too. Already-VSI (``/vsi*``) and local paths pass through unchanged.

    Args:
        url: Source dataset URL or path

    Returns:
        A GDAL-openable path for ST_Read.
    """
    if url.startswith('/vsi'):
        return url
    if url.startswith('s3://'):
        url = f"https://s3-west.nrp-nautilus.io/{url[len('s3://'):]}"
    if url.lower().startswith(('http://', 'https://')):
        return f"/vsicurl/{url}"
    return url


def _localize_gdb(source_url: str, verbose: bool = False) -> Tuple[str, Optional[str]]:
    """
    Copy a remote File Geodatabase (.gdb) to local disk and return its local path.

    A .gdb is a multi-file *directory*, not a single file, so GDAL/OGR ST_Read
    cannot open it over s3:// (and /vsis3 on a directory FileGDB is flaky across
    nodes). We mirror the raster path's rclone-based localization (issue #152):
    rclone copies the directory's objects to a temp dir and the rest of the
    pipeline reads the local .gdb.

    Only remote (s3://, http(s)://) .gdb sources are localized; local .gdb paths
    and non-.gdb sources pass through unchanged.

    Args:
        source_url: Source dataset URL or path
        verbose: Print debug information (also enables rclone progress)

    Returns:
        (local_or_original_path, temp_dir_to_cleanup). temp_dir_to_cleanup is
        None when no localization happened.
    """
    is_remote = source_url.startswith(('s3://', 'http://', 'https://'))
    if not (is_remote and _is_gdb_source(source_url)):
        return source_url, None

    if not shutil.which('rclone'):
        raise RuntimeError(
            f"Cannot localize remote File Geodatabase {source_url!r}: rclone not found. "
            "Install rclone or pre-stage the .gdb to a local path."
        )

    tmp_root = tempfile.mkdtemp(prefix='cng_gdb_')
    basename = os.path.basename(source_url.rstrip('/'))
    # rclone copies the *contents* of the source into the dest dir, so target the
    # .gdb subdir directly to reconstruct <tmp_root>/<name>.gdb/<objects>.
    local_path = os.path.join(tmp_root, basename)

    # Convert s3://bucket/path -> nrp:bucket/path for the standard NRP remote
    # name (matches _localize_input in the raster path).
    if source_url.startswith('s3://'):
        rclone_src = 'nrp:' + source_url[len('s3://'):]
    else:
        rclone_src = source_url

    print(f"  Remote File Geodatabase detected — localizing via rclone → {local_path}")
    cmd = ['rclone', 'copy', '--s3-no-check-bucket', '--transfers', '4',
           rclone_src, local_path]
    if verbose:
        cmd.append('-P')
    try:
        subprocess.run(cmd, check=True)
    except (subprocess.CalledProcessError, FileNotFoundError) as e:
        shutil.rmtree(tmp_root, ignore_errors=True)
        raise RuntimeError(f"rclone failed to localize {source_url!r}: {e}")

    return local_path, tmp_root


def download_and_extract(url: str, extract_to: str, verbose: bool = False) -> None:
    """
    Download a file from a URL and extract it if it is a zip file.

    Args:
        url: Source URL
        extract_to: Directory to extract to
        verbose: Print debug information
    """
    try:
        if verbose:
            print(f"  Downloading {url}...")

        # Handle S3 URLs via https if possible, otherwise rely on system tools or direct download
        # For simplicity, if it's s3-west.nrp-nautilus.io, we can use requests/urllib
        # If it's generic s3://, we might need boto3 or rclone?
        # For now, let's assume http/https or file path

        local_zip = os.path.join(extract_to, "downloadpkg.zip")

        if url.startswith("s3://"):
            path = url.replace("s3://", "")
            url = f"https://s3-west.nrp-nautilus.io/{path}"

        if url.startswith(("http://", "https://")):
            urlretrieve(url, local_zip)
        else:
            # Assume local file
            if os.path.exists(url):
                shutil.copy(url, local_zip)
            else:
                raise ValueError(f"File not found: {url}")

        if verbose:
            print("  Extracting zip file...")

        with zipfile.ZipFile(local_zip, 'r') as zip_ref:
            zip_ref.extractall(extract_to)

        # Cleanup zip
        os.remove(local_zip)

    except Exception as e:
        raise RuntimeError(f"Failed to download/extract zip: {e}")


# Geometry families that can share one GeoParquet column. A layer whose type
# GDAL cannot pin down ("Unknown", "Geometry") is compatible with anything.
_GEOMETRY_FAMILIES = {
    "point": "point", "multipoint": "point",
    "linestring": "line", "multilinestring": "line",
    "polygon": "polygon", "multipolygon": "polygon",
}


def _source_layers(source: str) -> Optional[List[str]]:
    """Layer names GDAL sees in *source*, or None if it cannot be listed."""
    try:
        import pyogrio
        return [str(row[0]) for row in pyogrio.list_layers(source)]
    except Exception:
        return None


def select_sources_for_layer(sources: List[str], layer: str) -> List[str]:
    """The sources in *sources* that actually contain *layer* (issue #216).

    `--layer` on an archive used to reach every source in it, and DuckDB's
    ST_Read segfaults when asked for a layer its source does not have — so a
    zip of a point and a polygon shapefile crashed whichever layer was asked
    for. A source whose layers cannot be listed is kept, and left to ST_Read.
    """
    keep, available = [], {}
    for src in sources:
        layers = _source_layers(src)
        if layers is None or layer in layers:
            keep.append(src)
        else:
            available[os.path.basename(src.rstrip("/"))] = layers
    if not keep:
        listing = "; ".join(f"{name}: {', '.join(ls) or '(none)'}"
                            for name, ls in available.items())
        raise ValueError(f"--layer {layer!r} is not in any source. Available layers: {listing}")
    return keep


def require_layer(source: str, layer: str) -> None:
    """Refuse a layer the source does not have, rather than crash on it.

    DuckDB's ST_Read segfaults on a missing layer (issue #216) — a typo in
    `--layer` would otherwise kill the process with no traceback at all.
    """
    layers = _source_layers(source)
    if layers is not None and layer not in layers:
        raise ValueError(
            f"--layer {layer!r} is not in {source}. Available layers: "
            f"{', '.join(layers) or '(none)'}")


def check_union_compatible(sources: List[str], layer: Optional[str] = None) -> None:
    """Refuse to UNION sources that cannot share one table (issue #216).

    The union is positional, so sources must agree on their columns, in order,
    and on geometry family. A mismatch in column count is already a DuckDB
    error, but equal counts with different columns would silently put values
    under the wrong names, and a point layer unioned with a polygon layer is
    never what a single-layer dataset means.
    """
    import pyogrio

    described = []
    for src in sources:
        try:
            info = pyogrio.read_info(src, layer=layer)
        except Exception:
            return  # cannot describe it; leave the union to DuckDB
        gtype = str(info.get("geometry_type") or "").lower().replace(" ", "")
        # "Polygon Z", "MultiLineString M", "Point ZM", "3D Polygon": the family
        # is what matters, not the dimensionality.
        family = _GEOMETRY_FAMILIES.get(re.sub(r"^(3d|2\.5d)|(zm|z|m|25d)$", "", gtype))
        fields = [str(f) for f in info.get("fields", [])]
        described.append((os.path.basename(src.rstrip("/")), family, fields, info.get("geometry_type")))

    families = {d[1] for d in described if d[1] is not None}
    schemas = {tuple(d[2]) for d in described}
    if len(families) <= 1 and len(schemas) <= 1:
        return
    lines = "\n".join(f"    {name}: {gtype}, columns {fields}"
                      for name, _, fields, gtype in described)
    problem = ("mixed geometry types" if len(families) > 1
               else "different columns")
    raise ValueError(
        f"Cannot merge these {len(sources)} sources into one table ({problem}):\n"
        f"{lines}\n"
        f"  Pick one with --layer <name>, or convert each separately.")


def find_vector_sources(directory: str) -> List[str]:
    """
    Recursively find vector sources in a directory.
    Returns .shp files if found; otherwise .gdb directories; otherwise .gpkg/.fgb files.
    """
    shapefiles = []
    gdbs = []
    others = []
    for root, dirs, files in os.walk(directory):
        for d in list(dirs):
            if d.lower().endswith(".gdb"):
                gdbs.append(os.path.join(root, d))
                dirs.remove(d)  # don't recurse into .gdb
        for file in files:
            low = file.lower()
            if low.endswith(".shp"):
                shapefiles.append(os.path.join(root, file))
            elif low.endswith((".gpkg", ".fgb")):
                others.append(os.path.join(root, file))
    return sorted(shapefiles) or sorted(gdbs) or sorted(others)


class DetectedCRS(NamedTuple):
    """
    Outcome of CRS detection, kept distinct so the caller can tell apart the
    three ways a source can lack an EPSG code (issue #187).

    Attributes:
        crs: What to hand ST_Transform — an authority string ("EPSG:4326") or,
            when the CRS carries no authority code, its full WKT definition.
            None only when there is no CRS to reproject from.
        kind: "code" (authority code), "definition" (WKT, no code available),
            "absent" (the dataset declares no CRS) or "undetectable"
            (detection itself failed).
        detail: The CRS name for "definition", the error for "undetectable".
    """
    crs: Optional[str]
    kind: str
    detail: str = ""


def detect_crs(source_input: str, layer: Optional[str] = None, verbose: bool = False) -> DetectedCRS:
    """
    Detect the CRS of a vector dataset using geopandas.

    A CRS with no EPSG code and no authority string is reported as a
    "definition" carrying its WKT rather than as no CRS at all. ST_Transform
    accepts WKT, so the reprojection path works unchanged — whereas returning
    None made the caller skip reprojection and tag projected metres as lon/lat
    (issue #187). Every MODIS-derived product ships such a CRS.

    Args:
        source_input: Source dataset URL or path
        layer: Layer name
        verbose: Print debug information

    Returns:
        DetectedCRS — see that class for how to read `kind`.
    """
    try:
        # Read just the first row to get CRS info quickly
        kwargs = {'rows': 1}
        if layer:
            kwargs['layer'] = layer

        # If source_input is a URL that geopandas can't handle directly without vsicurl, ensure it's handled
        # But for shapefiles on disk (which pass into here), it works fine.

        gdf = gpd.read_file(source_input, **kwargs)

        if gdf.crs is None:
            if verbose:
                print("Warning: No CRS found in dataset")
            return DetectedCRS(None, "absent")

        # Try to get EPSG code
        if gdf.crs.to_epsg():
            return DetectedCRS(f"EPSG:{gdf.crs.to_epsg()}", "code")

        # Fallback to authority string if available
        if gdf.crs.to_authority():
            auth, code = gdf.crs.to_authority()
            return DetectedCRS(f"{auth}:{code}", "code")

        # No code anywhere, but the CRS itself is fully specified — pass the
        # definition through instead of discarding it.
        if verbose:
            print(f"Note: CRS has no authority code, using its WKT definition: {gdf.crs}")
        return DetectedCRS(gdf.crs.to_wkt(), "definition", gdf.crs.name or "unnamed")

    except Exception as e:
        if verbose:
            print(f"Warning: CRS detection failed: {e}")
        return DetectedCRS(None, "undetectable", str(e))


_GEOM_COLUMN_NAMES = {'geom', 'geometry', 'shape', 'wkb_geometry'}


def unique_column_names(names: List[str]) -> List[str]:
    """Make repeated names unique: the second ``A`` becomes ``A_2`` (issue #314).

    DuckDB compares column names case-insensitively, so ``a`` and ``A``
    count as one name. A suffix that is itself taken moves on to the next
    number. The first occurrence always keeps its name.
    """
    taken = {n.lower() for n in names}
    seen = set()
    out = []
    for name in names:
        if name.lower() not in seen:
            seen.add(name.lower())
            out.append(name)
            continue
        k = 2
        while f"{name}_{k}".lower() in taken:
            k += 1
        new = f"{name}_{k}"
        taken.add(new.lower())
        out.append(new)
    return out


def _quote_ident(name: str) -> str:
    """Quote a SQL identifier, doubling any embedded double quote."""
    return '"' + name.replace('"', '""') + '"'


@functools.lru_cache(maxsize=64)
def st_read_sql(source: str, layer: Optional[str] = None) -> str:
    """The ``ST_Read(...)`` table expression for a source (issue #314).

    A source whose attribute table repeats a field name is common in
    shapefiles exported from ArcInfo coverages, which truncate names to 10
    characters. DuckDB refuses to bind it. In that case the columns are
    renamed with a positional alias, ``ST_Read(...) AS _src(a, b, ...)``,
    the repeats made unique by :func:`unique_column_names`. A source without
    repeats, or one OGR cannot describe, gets a bare ``ST_Read``.

    ST_Read's columns are the layer's FID (``OGC_FID`` unless the format
    names its own, such as ``fid`` in a GeoPackage), then the attribute
    fields in OGR's order, then the geometry. The alias covers the FID and
    the fields. The aliased result is checked, so that a different layout
    stops the conversion instead of putting values under the wrong names.
    """
    layer_param = f", layer='{layer}'" if layer else ""
    plain = f"ST_Read('{source}'{layer_param})"
    try:
        from osgeo import ogr
        ogr.UseExceptions()
        ds = ogr.Open(source)
        lyr = ds.GetLayerByName(layer) if layer else ds.GetLayer(0)
        defn = lyr.GetLayerDefn()
        fields = [defn.GetFieldDefn(i).GetName() for i in range(defn.GetFieldCount())]
        fid = lyr.GetFIDColumn() or "OGC_FID"
        n_geom = defn.GetGeomFieldCount()
        del lyr, ds
    except Exception:
        return plain
    if len({f.lower() for f in fields}) == len(fields):
        return plain

    renamed = unique_column_names([fid] + fields)
    changes = [f"{old} -> {new}" for old, new in zip([fid] + fields, renamed) if old != new]
    print(f"  Source repeats column names; renaming {', '.join(changes)}")
    aliased = f"{plain} AS _src({', '.join(_quote_ident(n) for n in renamed)})"

    con = duckdb.connect(':memory:')
    try:
        con.load_extension("spatial")
        cols = con.execute(f"DESCRIBE SELECT * FROM {aliased}").fetchall()
    finally:
        con.close()
    rest = cols[len(renamed):]
    if (len(rest) != n_geom
            or any(t.split("(")[0] not in ("GEOMETRY", "BLOB") for _, t, *_ in rest)):
        raise ValueError(
            f"Cannot rename the repeated columns of {source}: ST_Read returned "
            f"{[c[0] for c in cols]} for the fields {fields} (FID {fid}), not the "
            f"FID, the fields and {n_geom} geometry column(s) in that order. "
            f"Rename the fields first (e.g. ogr2ogr to GeoPackage).")
    return aliased


def get_geometry_column(source_url: str, layer: Optional[str] = None, verbose: bool = False) -> Tuple[str, bool]:
    """
    Get the name of the geometry column as seen by DuckDB.

    DuckDB's ST_Read returns GEOMETRY for most sources but returns BLOB for some
    geometry types (e.g. MULTIPOINT, M/Z variants).  When the column is typed as
    BLOB the caller must wrap it in ST_GeomFromWKB() before writing so that DuckDB
    emits a proper GEOMETRY column with GeoParquet metadata.

    Args:
        source_url: Source dataset URL
        layer: Layer name
        verbose: Print debug information

    Returns:
        Tuple of (column_name, is_wkb_blob) where is_wkb_blob is True when
        the column is typed BLOB and needs ST_GeomFromWKB() casting.
    """
    con = duckdb.connect(':memory:')
    con.install_extension("spatial")
    con.load_extension("spatial")
    con.execute("SET geometry_always_xy = true")  # (lon, lat) throughout (#280)
    con.execute("SET arrow_large_buffer_size=true")

    try:
        query = f"DESCRIBE SELECT * FROM {st_read_sql(source_url, layer)} LIMIT 0"

        columns = con.execute(query).fetchall()

        # First pass: proper GEOMETRY column
        for col_name, col_type, *_ in columns:
            if col_type == 'GEOMETRY':
                if verbose:
                    print(f"  Detected geometry column: {col_name}")
                return col_name, False

        # Second pass: BLOB column with a geometry-like name (e.g. MULTIPOINT sources)
        for col_name, col_type, *_ in columns:
            if col_type == 'BLOB' and col_name.lower() in _GEOM_COLUMN_NAMES:
                if verbose:
                    print(f"  Detected geometry column as BLOB (needs WKB cast): {col_name}")
                return col_name, True

        # Fallback: name-based detection (type unknown)
        col_map = {c[0].lower(): c[0] for c in columns}
        for name in ('geom', 'geometry', 'shape'):
            if name in col_map:
                return col_map[name], False

        if verbose:
            print("  Warning: Could not detect geometry column, defaulting to 'geom'")
        return "geom", False

    except Exception as e:
        if verbose:
            print(f"Warning: Geometry column detection failed: {e}")
        return "geom", False
    finally:
        con.close()


def check_id_column(source_url: str, layer: Optional[str] = None, id_column: Optional[str] = None,
                    force_id: bool = True, verbose: bool = False) -> Tuple[bool, str]:
    """
    Check if we need to create a synthetic _cng_fid row identifier.

    _cng_fid is always created as a monotonically increasing integer that is
    guaranteed unique per row.  Source columns such as 'fid' or 'objectid' are
    preserved unchanged — _cng_fid is additive.  Relying on source ID columns
    is unsafe because they may be feature/geometry identifiers rather than row
    identifiers (e.g. a dataset with multiple rows per site all sharing the same
    fid), which breaks the repartition join.

    Args:
        source_url: Source dataset URL
        layer: Layer name for multi-layer datasets (e.g., GDB)
        id_column: Explicit column name to use instead of _cng_fid (must exist in source)
        force_id: Unused; kept for backwards compatibility (always True in practice)
        verbose: Print debug information

    Returns:
        (needs_id, id_column_name) tuple where needs_id=True means the caller
        should call add_id_column_query() to prepend the synthetic ID.
    """
    con = duckdb.connect(':memory:')
    con.install_extension("spatial")
    con.load_extension("spatial")
    con.execute("SET geometry_always_xy = true")  # (lon, lat) throughout (#280)
    con.execute("SET arrow_large_buffer_size=true")

    try:
        columns = con.execute(f"""
            DESCRIBE SELECT * FROM {st_read_sql(source_url, layer)} LIMIT 0
        """).fetchall()

        column_names = [col[0].lower() for col in columns]

        # If user explicitly specified an ID column, use it (no synthetic ID needed)
        if id_column:
            if id_column.lower() in column_names:
                return False, id_column
            else:
                raise ValueError(f"Specified ID column '{id_column}' not found in source data")

        # If the source already has _cng_fid (e.g. re-processing), don't duplicate it
        if '_cng_fid' in column_names:
            if verbose:
                print("  Source already has _cng_fid — skipping synthetic ID creation")
            return False, "_cng_fid"

        # Always create a fresh _cng_fid — source ID columns (fid, objectid, etc.) are
        # not reliable as row keys and are preserved as-is alongside _cng_fid.
        if verbose:
            print("  Creating synthetic _cng_fid row identifier")
        return True, "_cng_fid"

    finally:
        con.close()


# Characters stripped from both ends of every string column when --trim-strings
# is set (issue #180). DuckDB's one-argument trim() removes ASCII spaces only, so
# the character set is passed explicitly to also catch tabs and stray newlines
# that GDB/Shapefile attribute values sometimes carry.
_TRIM_CHARS = " \\t\\n\\r"


def string_columns_from_describe(columns: List[tuple]) -> List[str]:
    """
    Pick the plain string columns out of a DuckDB DESCRIBE result.

    Only top-level VARCHAR columns are returned: those are the categorical
    attribute fields where stray leading/trailing whitespace silently breaks
    equality filters (issue #180). Nested types (VARCHAR[], STRUCT) are left
    alone — trimming inside them needs a different expression and no source has
    called for it.

    Args:
        columns: Rows from `DESCRIBE SELECT ...` — (column_name, column_type, ...)

    Returns:
        Names of the VARCHAR columns, in source order
    """
    return [name for name, col_type, *_ in columns if col_type.upper() == 'VARCHAR']


def get_string_columns(source_url: str, layer: Optional[str] = None,
                       verbose: bool = False) -> List[str]:
    """
    List the VARCHAR columns of an ST_Read-able source (issue #180).

    Args:
        source_url: Source dataset URL/path (GDAL-readable)
        layer: Layer name for multi-layer datasets (e.g. GDB)
        verbose: Print debug information

    Returns:
        Names of the VARCHAR columns; empty list if detection fails (trimming is
        an opt-in convenience, so a failed probe must not fail the conversion).
    """
    con = duckdb.connect(':memory:')
    con.install_extension("spatial")
    con.load_extension("spatial")
    con.execute("SET geometry_always_xy = true")  # (lon, lat) throughout (#280)
    con.execute("SET arrow_large_buffer_size=true")

    try:
        columns = con.execute(
            f"DESCRIBE SELECT * FROM {st_read_sql(source_url, layer)} LIMIT 0"
        ).fetchall()
        string_cols = string_columns_from_describe(columns)
        if verbose:
            print(f"  String columns: {string_cols}")
        return string_cols
    except Exception as e:
        print(f"  Warning: could not detect string columns ({e}) — "
              f"proceeding WITHOUT trimming")
        return []
    finally:
        con.close()


def trim_replace_clause(string_columns: Optional[List[str]],
                        exclude: Optional[List[str]] = None) -> str:
    """
    Build a DuckDB `REPLACE (...)` clause that trims each string column in place.

    Using star-REPLACE keeps the projection a one-liner per column and leaves
    every other column (and the source column order) untouched, so it composes
    with `* EXCLUDE (geom)` and the synthetic `_cng_fid` wrapper.

    Args:
        string_columns: VARCHAR column names to trim (None/empty -> no clause)
        exclude: Column names to skip (e.g. a geometry column already excluded
            from the star, which REPLACE cannot refer to)

    Returns:
        " REPLACE (trim(...) AS ...)" or "" when there is nothing to trim
    """
    skip = {c.lower() for c in (exclude or [])}
    cols = [c for c in (string_columns or []) if c.lower() not in skip]
    if not cols:
        return ""
    replacements = ", ".join(
        f'trim("{c}", E\'{_TRIM_CHARS}\') AS "{c}"' for c in cols
    )
    return f" REPLACE ({replacements})"


def _sql_string(value: str) -> str:
    """Quote a value as a SQL string literal, doubling any embedded quote."""
    escaped = value.replace("'", "''")
    return f"'{escaped}'"


# DuckDB function that splits a (lon, lat) geometry at the antimeridian
# (registered by write_with_duckdb, issue #274).
DATELINE_UDF = "cng_split_dateline"


def is_geographic_target(target_crs: str) -> bool:
    """Whether target_crs is geographic, so an antimeridian exists to split at."""
    from osgeo import osr
    srs = osr.SpatialReference()
    srs.SetFromUserInput(target_crs)
    return bool(srs.IsGeographic())


def split_dateline_wkb(wkb: bytes) -> bytes:
    """Split a (lon, lat) geometry whose rings run the long way round at 180°.

    A feature that crosses 180° in a projected source comes out of
    ST_Transform with vertices on both sides, joined the long way round
    (issue #274). Shifting the negative longitudes by 360 makes it continuous
    again; it is then cut at 180 and the eastern piece shifted back. A
    feature still wider than 180° after the shift genuinely spans that much
    and is returned unchanged.

    DuckDB spatial has no antimeridian split, and GDAL's WRAPDATELINE leaves
    some projections unsplit (EPSG:3338, Alaska Albers), so this is done here.

    An invalid feature (a self-intersecting ring, say) is repaired before the
    cut, because GEOS's intersection raises on it and would abort the whole
    conversion (issue #315). Validity is judged in the shifted frame, where
    the feature has its true shape. The repair is ``make_valid``, the same
    GEOS routine as the ST_MakeValid that every other feature gets after
    reprojection, so a crosser comes out as it would anywhere else.

    A polygon that contains a pole (from a polar CRS such as EPSG:3413 or
    EPSG:3031) has a ring that winds all the way round in longitude, and no
    shift makes it continuous. It is closed along the pole and cut into
    -180..180 instead (issue #322; see _split_polar).
    """
    import numpy as np
    import shapely
    from shapely import affinity

    geom = shapely.from_wkb(wkb)
    if _winds_round_a_pole(geom):
        return shapely.to_wkb(_split_polar(geom))
    shifted = shapely.transform(
        geom, lambda c: np.where(c[:, :1] < 0, c + [360.0, 0.0], c))
    if not shapely.is_valid(shifted):
        shifted = shapely.make_valid(shifted)
    xmin, _, xmax, _ = shifted.bounds
    if xmax - xmin >= 180:
        return wkb
    west = shifted.intersection(shapely.box(xmin, -90, 180, 90))
    east = affinity.translate(
        shifted.intersection(shapely.box(180, -90, xmax, 90)), xoff=-360)
    return shapely.to_wkb(shapely.union(west, east))


def _polygon_parts(geom) -> list:
    """The polygons of a Polygon or MultiPolygon; empty for any other type."""
    if geom.geom_type == "Polygon":
        return [geom]
    if geom.geom_type == "MultiPolygon":
        return list(geom.geoms)
    return []


def _unwrap_ring(ring):
    """A ring's (lon, lat) coordinates with each step taken the short way
    round, so longitude runs continuously past ±180, and the ring's net
    change in longitude: 0 for an ordinary ring, ±360 for one round a pole."""
    import numpy as np
    import shapely
    xy = shapely.get_coordinates(ring)
    steps = (np.diff(xy[:, 0]) + 180.0) % 360.0 - 180.0
    lon = xy[0, 0] + np.concatenate([[0.0], np.cumsum(steps)])
    return np.column_stack([lon, xy[:, 1]]), lon[-1] - lon[0]


def _winds_round_a_pole(geom) -> bool:
    """Whether any ring of a (lon, lat) polygon goes all the way round in
    longitude, which in a valid source means it encloses a pole."""
    return any(abs(_unwrap_ring(r)[1]) > 180
               for p in _polygon_parts(geom)
               for r in [p.exterior, *p.interiors])


def _ring_as_polygon(ring):
    """A ring as a polygon in an unwrapped longitude frame. A ring round a
    pole becomes the cap it bounds: its path from lon0 to lon0 ± 360 is closed
    along the pole on the side of its own latitudes (issue #322)."""
    import numpy as np
    import shapely
    xy, winding = _unwrap_ring(ring)
    if abs(winding) > 180:
        pole = 90.0 if xy[:, 1].mean() > 0 else -90.0
        xy = np.vstack([xy, [[xy[-1, 0], pole], [xy[0, 0], pole], xy[0]]])
    poly = shapely.Polygon(xy)
    return poly if poly.is_valid else shapely.make_valid(poly)


def _wrap_to_world(geom):
    """Cut a geometry in an unwrapped longitude frame into -180..180."""
    import math
    import shapely
    from shapely import affinity
    xmin, _, xmax, _ = geom.bounds
    pieces = []
    for k in range(math.floor((xmin + 180) / 360), math.ceil((xmax - 180) / 360) + 1):
        piece = geom.intersection(shapely.box(360 * k - 180, -90, 360 * k + 180, 90))
        if not piece.is_empty:
            pieces.append(affinity.translate(piece, xoff=-360 * k))
    return shapely.union_all(pieces)


def _split_polar(geom):
    """A (lon, lat) polygon with a ring round a pole, as valid -180..180
    polygons.

    ST_Transform out of a polar CRS writes a pole-containing polygon as a
    ring with a vertex at every longitude. Read flat, that ring encloses
    nothing, and ST_MakeValid reduced it to lines (a cap at 80° N came out
    with zero area, issue #322). Here each ring is unwrapped, a ring round a
    pole is closed along that pole, and every ring is cut into -180..180 on
    its own before the holes are taken out, so rings never have to share a
    longitude frame. The pole is the one on the side of the ring's own
    latitudes, which is the enclosed one for any ring that lies in a single
    hemisphere.
    """
    import shapely
    parts = []
    for poly in _polygon_parts(geom):
        shell = _wrap_to_world(_ring_as_polygon(poly.exterior))
        holes = [_wrap_to_world(_ring_as_polygon(r)) for r in poly.interiors]
        parts.append(shell.difference(shapely.union_all(holes)) if holes else shell)
    return shapely.union_all(parts)


def register_dateline_split(con) -> None:
    """Register DATELINE_UDF (split_dateline_wkb) on a DuckDB connection."""
    con.create_function(DATELINE_UDF, split_dateline_wkb, ["BLOB"], "BLOB",
                        side_effects=False)


def geometry_sql(raw_geom: str, source_crs: Optional[str], target_crs: str,
                 wrap_dateline: bool = False,
                 simplify_tolerance: Optional[float] = None) -> str:
    """SQL for a source geometry as written to the output: reprojected to
    target_crs when source_crs differs, split at the antimeridian when
    wrap_dateline (issue #274), simplified when asked (issue #132), and
    repaired with ST_MakeValid.

    Every source goes through this, whether read with ST_Read or, for a
    GeoParquet source, with read_parquet (issue #327), so the two paths
    cannot drift apart.
    """
    # Determine geometry transformation
    if source_crs and source_crs != target_crs:
        # Need to reproject. DuckDB's ST_Transform honours each CRS's *authority* axis
        # order by default (e.g. EPSG:4326 is latitude-first), but GeoParquet — and
        # DuckDB's own ST_Read — always store coordinates as (longitude, latitude).
        # Passing always_xy := true forces ST_Transform to read AND write (lon, lat)
        # regardless of either CRS's declared axis order, so the output is always
        # (lon, lat) and no ST_FlipCoordinates correction is needed.
        #
        # This replaces an earlier is_geographic_crs() heuristic that decided whether
        # to flip based on a numeric EPSG-code range. That heuristic mis-handled
        # axis-order edge cases — geographic CRSs that are longitude-first (OGC:CRS84)
        # and geographic compound/3D CRSs with codes >= 5000 (EPSG:5498
        # "NAD83 + NAVD88 height", EPSG:4979) — swapping lat/lon for them (see #128).
        # The source CRS may now be a full WKT definition rather than a short
        # "EPSG:4326" token (issue #187), and a definition can carry a quote in
        # a datum or projection name, so both operands are escaped before they
        # reach the query.
        geom_inner = (
            f"ST_Transform({raw_geom}, {_sql_string(source_crs)}, "
            f"{_sql_string(target_crs)}, always_xy := true)"
        )
        if wrap_dateline:
            # A crosser comes out of ST_Transform wider than 180°. The split
            # leaves a feature that is genuinely that wide alone, so the bbox
            # test only decides which features take the slower path.
            geom_inner = (
                f"(CASE WHEN ST_XMax({geom_inner}) - ST_XMin({geom_inner}) > 180 "
                f"THEN ST_GeomFromWKB({DATELINE_UDF}(ST_AsWKB({geom_inner}))) "
                f"ELSE {geom_inner} END)"
            )
    else:
        # No reprojection needed; DuckDB ST_Read and read_parquet return (lon, lat)
        geom_inner = raw_geom

    # Simplify after reprojection (tolerance is in target-CRS units, issue #132).
    # PreserveTopology avoids collapsing polygons into invalid/empty geometry.
    if simplify_tolerance is not None:
        geom_inner = f"ST_SimplifyPreserveTopology({geom_inner}, {simplify_tolerance})"

    return f"ST_MakeValid({geom_inner})"


def build_read_reproject_query(source_inputs: Union[str, List[str]], source_crs: Optional[str],
                               target_crs: str, geom_col: str = "geom", layer: Optional[str] = None,
                               verbose: bool = False, geom_is_blob: bool = False,
                               simplify_tolerance: Optional[float] = None,
                               trim_columns: Optional[List[str]] = None,
                               wrap_dateline: bool = False) -> str:
    """
    Build DuckDB query to read and reproject data. Can handle multiple input files.

    Args:
        source_inputs: Source dataset URL or list of file paths
        source_crs: Source CRS — an authority string ("EPSG:3857") or a full WKT
            definition for a CRS with no authority code (None = no reprojection needed)
        target_crs: Target CRS
        geom_col: Geometry column name
        layer: Layer name
        verbose: Print debug information
        geom_is_blob: When True the geometry column is typed BLOB (e.g. MULTIPOINT sources)
            and must be cast to GEOMETRY via ST_GeomFromWKB() before any spatial operation.
        simplify_tolerance: When set, simplify each geometry to this tolerance (in
            target-CRS units) via ST_SimplifyPreserveTopology, applied AFTER
            reprojection so the tolerance is in the output CRS (issue #132).
        trim_columns: String columns to strip leading/trailing whitespace from
            (--trim-strings, issue #180). Applied via star-REPLACE so every other
            column, and the column order, is untouched.
        wrap_dateline: Pass any feature whose result is wider than 180° to
            DATELINE_UDF, which splits it at the antimeridian (issue #274). The
            connection running the query must have it registered.

    Returns:
        DuckDB SQL query string
    """
    # When geometry is a BLOB (e.g. MULTIPOINT) we must cast it first so that
    # downstream operations (ST_Transform, COPY TO parquet) see a GEOMETRY column
    # and DuckDB writes proper GeoParquet metadata.
    raw_geom = f"ST_GeomFromWKB({geom_col})" if geom_is_blob else geom_col

    geom_expr = (
        f"{geometry_sql(raw_geom, source_crs, target_crs, wrap_dateline=wrap_dateline, simplify_tolerance=simplify_tolerance)} "
        f"AS {geom_col}"
    )

    # Trim string attributes in place (issue #180). REPLACE cannot name the
    # geometry column, which the star already excludes, so it is filtered out.
    replace_clause = trim_replace_clause(trim_columns, exclude=[geom_col])

    # helper to format a single SELECT
    def make_select(src):
        return f"""
        SELECT
            * EXCLUDE ({geom_col}){replace_clause},
            {geom_expr}
        FROM {st_read_sql(src, layer)}
        """

    if isinstance(source_inputs, list):
        # Union all inputs
        selects = [make_select(src) for src in source_inputs]
        query = "\nUNION ALL\n".join(selects)
    else:
        query = make_select(source_inputs)

    if verbose:
        print(f"Read/Reproject Query (preview): {query[:500]}...")

    return query


def add_id_column_query(base_query: str, id_column: str = "_cng_fid") -> str:
    """
    Wrap a query to add a synthetic ID column.

    Args:
        base_query: Base query that reads/reprojects data
        id_column: Name of ID column to create

    Returns:
        Wrapped query with ID column
    """
    return f"""
    SELECT
        ROW_NUMBER() OVER () AS {id_column},
        *
    FROM ({base_query})
    """


# The whole lon/lat plane, as the Hilbert curve's extent for geographic output.
# ST_Hilbert encodes 16 bits per axis, so a cell is about 0.0055 deg (~600 m),
# far finer than a row group.
WORLD_BOX = "{'min_x': -180, 'min_y': -90, 'max_x': 180, 'max_y': 90}::BOX_2D"


def spatial_order_query(base_query: str, geom_col: str, id_column: Optional[str] = None,
                        geographic: bool = True) -> str:
    """
    Order rows along a Hilbert curve, numbering them in that order (issue #276).

    Nearby features land in the same row groups, so the geometry statistics
    prune by location, as Portolan requires of GeoParquet. Numbering
    ``id_column`` in the same order carries that locality into the hex output,
    where repartition orders rows by id: a feature's cells stay together, which
    compresses its repeated attributes, and a county query reads few row groups.

    Args:
        base_query: Query producing the rows, with a GEOMETRY column ``geom_col``
        geom_col: Geometry column to order by (the centre of its bbox is encoded)
        id_column: Synthetic id to number in Hilbert order; None keeps the
            source's own id and only orders the rows
        geographic: The output is lon/lat, so the curve spans the whole plane.
            Otherwise it spans the data's own extent, computed in a first pass.

    Returns:
        Query with rows in Hilbert order (null geometries last)
    """
    if geographic:
        source, box = f"({base_query}) AS src", WORLD_BOX
    else:
        source = f"({base_query}) AS src, (SELECT ST_Extent(ST_Extent_Agg(\"{geom_col}\")) AS box FROM ({base_query})) AS b"
        box = "b.box"
    key = f'ST_Hilbert(src."{geom_col}", {box})'
    if id_column:
        return f"""
    SELECT ROW_NUMBER() OVER (ORDER BY {key} NULLS LAST) AS {id_column}, src.*
    FROM {source}
    ORDER BY {id_column}
    """
    return f"""
    SELECT src.* FROM {source}
    ORDER BY {key} NULLS LAST
    """


def parquet_type_crs(column_type: str) -> Optional[str]:
    """The CRS DuckDB attached to a GEOMETRY column type read from GeoParquet:
    ``GEOMETRY('EPSG:3338')`` gives ``EPSG:3338``, and a CRS with no code
    gives its PROJJSON. None for a plain GEOMETRY or a BLOB (issue #327)."""
    t = column_type.strip()
    if not (t.upper().startswith("GEOMETRY('") and t.endswith("')")):
        return None
    return t[len("GEOMETRY('"):-2].replace("''", "'") or None


def same_crs(a: str, b: str) -> bool:
    """Whether two CRS strings name the same CRS, ignoring axis order, which
    ST_Transform's always_xy makes irrelevant (so OGC:CRS84 is EPSG:4326)."""
    if a == b:
        return True
    from osgeo import osr
    sa, sb = osr.SpatialReference(), osr.SpatialReference()
    try:
        sa.SetFromUserInput(a)
        sb.SetFromUserInput(b)
    except RuntimeError:
        return False
    return bool(sa.IsSame(sb, ["CRITERION=EQUIVALENT_EXCEPT_AXIS_ORDER_GEOGCRS"]))


def process_parquet_input(
    source_url: str,
    destination: str,
    compression: str = "ZSTD",
    compression_level: int = 15,
    row_group_size: int = 100000,
    id_column: Optional[str] = None,
    force_id: bool = True,
    progress: bool = True,
    target_crs: str = "EPSG:4326",
    verbose: bool = False,
    simplify_tolerance: Optional[float] = None,
    trim_strings: bool = False,
    expect_features: Optional[int] = None,
    spatial_order: bool = True,
):
    """
    Process a parquet input file to ensure it has global ID and cloud optimization.

    When the input is already parquet, we use DuckDB to read it directly
    without using ST_Read, ensuring we have an ID column and applying
    GeoParquet optimizations. Its geometry is reprojected from the CRS in its
    GeoParquet metadata, split at the antimeridian and repaired exactly as for
    any other source (issue #327).

    Args:
        source_url: Source parquet URL (supports s3://, http://, file paths)
        destination: Output path (s3:// or local file path)
        compression: Compression algorithm (ZSTD, GZIP, SNAPPY, NONE)
        compression_level: Compression level (1-22 for ZSTD)
        row_group_size: Number of rows per group
        id_column: Specific source column to use as the row id instead of
            synthesizing _cng_fid (must exist in source)
        force_id: Unused; kept for backwards compatibility (_cng_fid is always
            created unless id_column is given or the source already has it)
        progress: Show progress during conversion
        target_crs: Target CRS for output (default: EPSG:4326)
        verbose: Print detailed debug information
        simplify_tolerance: Optional geometry simplification tolerance in
            target-CRS units, applied after reprojection (issue #132)
        trim_strings: Strip leading/trailing whitespace from every VARCHAR column
            (issue #180)
        expect_features: Row count this conversion is expected to produce, known
            independently by the caller (issue #186). The count is always logged;
            when this is given and the written count differs, the conversion
            raises FeatureCountMismatch so a pipeline can gate on it.
        spatial_order: Write rows in Hilbert order of their geometry and
            number a synthetic _cng_fid in that order (issue #276). Turn off to
            keep source order, e.g. when the sort will not fit the pod.
    """
    print(f"Processing parquet file: {source_url}")
    print(f"               Output to: {destination}")

    if progress:
        print(f"  Compression: {compression} level {compression_level}")
        print(f"  Row group size: {row_group_size:,}")

    con = duckdb.connect(':memory:')
    con.install_extension("spatial")
    con.load_extension("spatial")
    con.execute("SET geometry_always_xy = true")  # (lon, lat) throughout (#280)

    # Enable large buffer size for complex geometries
    con.execute("SET arrow_large_buffer_size=true")

    try:
        # Convert s3:// URLs to GDAL format for reading
        read_url = source_url
        if source_url.startswith('s3://'):
            # DuckDB spatial extension can read from vsicurl
            path = source_url.replace('s3://', '')
            read_url = f"https://s3-west.nrp-nautilus.io/{path}"

        # Check for ID column
        print("  Checking for ID column...")
        columns = con.execute(f"""
            DESCRIBE SELECT * FROM read_parquet('{read_url}') LIMIT 0
        """).fetchall()

        column_names = [col[0].lower() for col in columns]

        # Determine ID handling. Always create a synthetic _cng_fid row
        # identifier (issue #43) unless the user named an explicit id_column or
        # the source already carries _cng_fid. Source columns such as 'fid',
        # 'objectid', etc. are NOT trusted as row keys — they may be
        # feature/geometry identifiers with multiple rows per value (e.g. the
        # TPL Conservation Almanac's 'fid', one row per funding program per
        # site), which makes the repartition join many-to-many. They are
        # preserved unchanged alongside _cng_fid (matching check_id_column for
        # the ST_Read path). force_id is accepted for backwards compatibility
        # but always treated as True.
        needs_id = False
        id_col_name = None

        if id_column:
            if id_column.lower() in column_names:
                id_col_name = id_column
            else:
                raise ValueError(f"Specified ID column '{id_column}' not found in source data")
        elif '_cng_fid' in column_names:
            # Re-processing an already-converted dataset; don't duplicate it.
            id_col_name = "_cng_fid"
        else:
            needs_id = True
            id_col_name = "_cng_fid"

        if needs_id:
            print(f"  Adding synthetic ID column: {id_col_name}")
        else:
            print(f"  Using existing ID column: {id_col_name}")

        # Classify the geometry column. DuckDB ingests a native GEOMETRY column
        # directly, and a BLOB-typed WKB column via ST_GeomFromWKB (e.g.
        # MULTIPOINT — issue #61); without that cast DuckDB writes BLOB back with
        # no GeoParquet metadata and the PMTiles step produces null geometries.
        # Any OTHER encoding read_parquet exposes — notably geoarrow-native (a
        # STRUCT column) or WKT (VARCHAR) — cannot be operated on by DuckDB and
        # would otherwise pass through verbatim as a non-GEOMETRY column with no
        # GeoParquet metadata, silently breaking every downstream consumer
        # (issue #119). Detect that and fail with an actionable message.
        has_geometry = any(ct.upper().startswith('GEOMETRY') for _, ct, *_ in columns)
        geom_blob_col = None
        geom_native_col = None  # name of a native GEOMETRY-typed column
        geom_unsupported = None  # (name, type) of a geom-named column we can't ingest
        for col_name, col_type, *_ in columns:
            if col_name.lower() not in _GEOM_COLUMN_NAMES:
                continue
            ct = col_type.upper()
            if ct == 'BLOB':
                geom_blob_col = col_name
            elif ct.startswith('GEOMETRY'):
                geom_native_col = col_name
            else:
                geom_unsupported = (col_name, col_type)

        # Only error when there is no usable geometry at all (no native GEOMETRY,
        # no castable BLOB) but a geom-named column exists in an encoding we can't
        # handle. This avoids false positives when a real GEOMETRY column
        # coexists with, say, a numeric column named "shape".
        if not has_geometry and geom_blob_col is None and geom_unsupported is not None:
            bad_name, bad_type = geom_unsupported
            raise ValueError(
                f"Geometry column '{bad_name}' has type {bad_type}, which DuckDB "
                f"cannot ingest directly (typically geoarrow-native or WKT "
                f"encoding). DuckDB is the supported engine; re-encode the source "
                f"as WKB GeoParquet first and re-run, e.g.:\n"
                f"    ogr2ogr -f Parquet fixed.parquet '{source_url}'\n"
                f"  or in Python:\n"
                f"    geopandas.read_parquet('{source_url}')"
                f".to_parquet('fixed.parquet', geometry_encoding='WKB')"
            )

        # Trim string attributes in place when asked (issue #180). Computed from
        # the same DESCRIBE used above; the geometry column can never be VARCHAR
        # here (it is GEOMETRY or BLOB), but exclude it anyway for safety since
        # REPLACE cannot name a column the star excludes.
        trim_clause = ""
        if trim_strings:
            string_cols = string_columns_from_describe(columns)
            trim_clause = trim_replace_clause(
                string_cols, exclude=[c for c in (geom_blob_col, geom_native_col) if c]
            )
            print(f"  Trimming whitespace from {len(string_cols)} string column(s)")

        # Build the geometry the same way as for any other source (issue #327):
        # reproject to target_crs, split at the antimeridian, simplify, and
        # repair with ST_MakeValid. A BLOB WKB column is cast to GEOMETRY first.
        geom_name = geom_blob_col or geom_native_col
        split_dateline = False
        geographic = False
        if geom_name:
            if geom_blob_col:
                print(f"  Casting BLOB geometry column to GEOMETRY: {geom_name}")
            base_geom = f'ST_GeomFromWKB("{geom_name}")' if geom_blob_col else f'"{geom_name}"'
            # DuckDB reads a GeoParquet column's CRS into its type. A file that
            # names none reads as OGC:CRS84, as the GeoParquet spec says. A
            # BLOB column has no GeoParquet metadata, so no CRS.
            geom_type = next(t for n, t, *_ in columns if n == geom_name)
            source_crs = parquet_type_crs(geom_type)
            reproject_from = None
            if source_crs is None:
                print(f"  Warning: geometry column declares no CRS, assuming {target_crs}")
            elif same_crs(source_crs, target_crs):
                print(f"  Source already in {target_crs}")
            else:
                shown = source_crs if len(source_crs) < 60 else "a PROJJSON definition"
                print(f"  Source CRS: {shown} -> Reprojecting to {target_crs}")
                reproject_from = source_crs
            split_dateline = reproject_from is not None and is_geographic_target(target_crs)
            # A file with no CRS reads as OGC:CRS84 too, so CRS84 is no proof of
            # lon/lat coordinates. Order over the lon/lat plane only when this
            # step reprojected the data there itself.
            geographic = split_dateline
            if simplify_tolerance is not None:
                print(f"  Simplifying geometry with tolerance {simplify_tolerance} (target-CRS units)")
            geom_sql = geometry_sql(base_geom, reproject_from, target_crs,
                                    wrap_dateline=split_dateline,
                                    simplify_tolerance=simplify_tolerance)
            # A source's own bbox covering column (an Overture file, or one
            # converted here before) describes the geometry as it was, before
            # reprojection and repair. Drop it; the write adds a fresh one (#340).
            stale = "".join(f', "{c}"' for c in covering_columns(con, read_url)
                            if c != geom_name)
            cols_expr = (f'* EXCLUDE ("{geom_name}"{stale}){trim_clause}, '
                         f'{geom_sql} AS "{geom_name}"')
        else:
            cols_expr = f"*{trim_clause}"

        # Build query to read, cast geometry, and optionally add ID. The
        # Hilbert curve spans the lon/lat plane when this step reprojected to
        # lon/lat, and the data's own extent otherwise (issue #276).
        if spatial_order and geom_name:
            print("  Ordering rows along a Hilbert curve"
                  + (f" and numbering {id_col_name} in that order" if needs_id else ""))
            query = spatial_order_query(
                f"SELECT {cols_expr} FROM read_parquet('{read_url}')", geom_name,
                id_col_name if needs_id else None, geographic=geographic)
        elif needs_id:
            query = f"""
            SELECT
                ROW_NUMBER() OVER () AS {id_col_name},
                {cols_expr}
            FROM read_parquet('{read_url}')
            """
        else:
            query = f"""
            SELECT {cols_expr} FROM read_parquet('{read_url}')
            """

        # Write with DuckDB
        is_s3_dest = destination.startswith('s3://')

        if is_s3_dest:
            # Write to temp file first
            with tempfile.NamedTemporaryFile(suffix='.parquet', delete=False) as tmp:
                tmp_path = tmp.name

            try:
                if verbose:
                    print(f"  Writing to temporary file: {tmp_path}")

                rows_written = write_with_duckdb(query, tmp_path, compression, compression_level,
                                row_group_size, verbose, split_dateline=split_dateline)
                # Checked before the upload, so a short read never reaches the
                # bucket to be consumed by anything downstream (issue #186).
                _report_row_count(rows_written, expect_features)

                # Upload to S3
                upload_to_s3(tmp_path, destination, verbose=progress)

            finally:
                if os.path.exists(tmp_path):
                    os.unlink(tmp_path)
        else:
            # Write directly to destination
            rows_written = write_with_duckdb(query, destination, compression, compression_level,
                            row_group_size, verbose, split_dateline=split_dateline)
            _report_row_count(rows_written, expect_features)

        print("✓ Parquet processing completed successfully!")

    except Exception as e:
        print(f"✗ Parquet processing failed: {e}", file=sys.stderr)
        if verbose:
            import traceback
            traceback.print_exc()
        raise
    finally:
        con.close()


def process_csv_input(
    source_url: str,
    destination: str,
    lat_column: Optional[str] = None,
    lon_column: Optional[str] = None,
    compression: str = "ZSTD",
    compression_level: int = 15,
    row_group_size: int = 100000,
    id_column: Optional[str] = None,
    force_id: bool = True,
    progress: bool = True,
    target_crs: str = "EPSG:4326",
    verbose: bool = False,
    simplify_tolerance: Optional[float] = None,
    trim_strings: bool = False,
    expect_features: Optional[int] = None,
    csv_sample_size: int = -1,
    spatial_order: bool = True,
):
    """
    Convert a CSV with latitude/longitude columns into point GeoParquet (issue #78).

    The lat/lon columns are read as WGS84 (EPSG:4326) coordinates and turned into
    a Point ``geom`` column via ST_Point(lon, lat) (GeoParquet (lon, lat) order).
    All source columns — including the lat/lon columns — are carried through as
    attributes, and a synthetic ``_cng_fid`` is added as usual.

    Args:
        source_url: Source CSV/TSV URL (s3://, http(s)://, or local path)
        destination: Output GeoParquet path (s3:// or local)
        lat_column: Latitude column name (auto-detected if not given)
        lon_column: Longitude column name (auto-detected if not given)
        compression, compression_level, row_group_size: Parquet write options
        id_column: Source column to use as row id instead of synthesizing _cng_fid
        force_id: Kept for backwards compatibility (_cng_fid always created)
        progress: Show progress messages
        target_crs: Output CRS. Points are built in EPSG:4326 and reprojected if
            this differs.
        verbose: Print detailed debug information
        simplify_tolerance: Unused for points (kept for a uniform call signature)
        trim_strings: Strip leading/trailing whitespace from every VARCHAR column
            (issue #180)
        expect_features: Row count this conversion is expected to produce, known
            independently by the caller (issue #186). The count is always logged;
            when this is given and the written count differs, the conversion
            raises FeatureCountMismatch so a pipeline can gate on it.
        csv_sample_size: Rows read_csv_auto samples for type inference. -1 (the
            default) scans the whole file, so a numeric column that is entirely
            NULL in the head of the file is still typed numerically rather than
            as VARCHAR (issue #188).
        spatial_order: Write rows in Hilbert order of their geometry and
            number a synthetic _cng_fid in that order (issue #276). Turn off to
            keep source order, e.g. when the sort will not fit the pod.
    """
    print(f"Processing CSV point file: {source_url}")
    print(f"                Output to: {destination}")

    con = duckdb.connect(':memory:')
    con.install_extension("spatial")
    con.load_extension("spatial")
    con.execute("SET geometry_always_xy = true")  # (lon, lat) throughout (#280)
    con.execute("SET arrow_large_buffer_size=true")

    try:
        read_url = source_url
        if source_url.startswith('s3://'):
            read_url = f"https://s3-west.nrp-nautilus.io/{source_url[len('s3://'):]}"

        # Type inference reads csv_sample_size rows; -1 scans the whole file.
        # DuckDB's 20480-row default types a column that is entirely NULL in the
        # head of the file as VARCHAR even when it is cleanly numeric further
        # down — the normal shape for a time-ordered file with columns
        # introduced in a later reporting era (issue #188). The same reader
        # argument is used for the range check and the write below, so all three
        # agree on the schema.
        csv_read = f"read_csv_auto('{read_url}', sample_size={int(csv_sample_size)})"
        if csv_sample_size != -1:
            print(f"  Type inference sample: {csv_sample_size:,} rows "
                  f"(a late-appearing numeric column may be typed VARCHAR)")

        # Detect columns
        columns = con.execute(
            f"DESCRIBE SELECT * FROM {csv_read} LIMIT 0"
        ).fetchall()
        column_names = [col[0] for col in columns]
        column_names_lower = [c.lower() for c in column_names]

        lat_col, lon_col = _resolve_latlon_columns(column_names, lat_column, lon_column)
        print(f"  Latitude column:  {lat_col}")
        print(f"  Longitude column: {lon_col}")

        # ID handling mirrors process_parquet_input: always synthesize _cng_fid
        # unless the user named an explicit id_column or the source already has it.
        needs_id = False
        if id_column:
            if id_column.lower() not in column_names_lower:
                raise ValueError(f"Specified ID column '{id_column}' not found in CSV")
            id_col_name = id_column
        elif '_cng_fid' in column_names_lower:
            id_col_name = "_cng_fid"
        else:
            needs_id = True
            id_col_name = "_cng_fid"
        print(f"  {'Adding synthetic' if needs_id else 'Using existing'} ID column: {id_col_name}")

        # Warn on out-of-range coordinates (commonly swapped lat/lon columns).
        bad = con.execute(f"""
            SELECT
                COUNT(*) FILTER (WHERE abs(CAST("{lat_col}" AS DOUBLE)) > 90) AS bad_lat,
                COUNT(*) FILTER (WHERE abs(CAST("{lon_col}" AS DOUBLE)) > 180) AS bad_lon
            FROM {csv_read}
            WHERE "{lat_col}" IS NOT NULL AND "{lon_col}" IS NOT NULL
        """).fetchone()
        if bad and (bad[0] or bad[1]):
            print(
                f"  Warning: {bad[0]} rows have |latitude| > 90 and {bad[1]} have "
                f"|longitude| > 180. Check that --lat-column/--lon-column are not swapped."
            )

        # Build the point geometry in EPSG:4326, reprojecting only if the target
        # differs. NULL coordinates yield NULL geometry (kept, hexes to nothing).
        point_expr = (
            f'CASE WHEN "{lon_col}" IS NOT NULL AND "{lat_col}" IS NOT NULL '
            f'THEN ST_Point(CAST("{lon_col}" AS DOUBLE), CAST("{lat_col}" AS DOUBLE)) '
            f'ELSE NULL END'
        )
        if target_crs and target_crs != "EPSG:4326":
            point_expr = f"ST_Transform({point_expr}, 'EPSG:4326', '{target_crs}', always_xy := true)"
        geom_expr = f"ST_MakeValid({point_expr}) AS geom"

        # Trim string attributes in place when asked (issue #180). The lat/lon
        # columns are numeric after read_csv_auto's type inference, so they are
        # untouched even when they are carried through as attributes.
        trim_clause = ""
        if trim_strings:
            string_cols = string_columns_from_describe(columns)
            trim_clause = trim_replace_clause(string_cols)
            print(f"  Trimming whitespace from {len(string_cols)} string column(s)")

        if spatial_order:
            # Ordered over the points' own extent: out-of-range coordinates are
            # only warned about above, and the target may be projected.
            print("  Ordering rows along a Hilbert curve"
                  + (f" and numbering {id_col_name} in that order" if needs_id else ""))
            query = spatial_order_query(
                f"SELECT *{trim_clause}, {geom_expr} FROM {csv_read}", "geom",
                id_col_name if needs_id else None, geographic=False)
        else:
            id_prefix = f"ROW_NUMBER() OVER () AS {id_col_name}, " if needs_id else ""
            query = f"""
                SELECT {id_prefix}*{trim_clause}, {geom_expr}
                FROM {csv_read}
            """

        is_s3_dest = destination.startswith('s3://')
        if is_s3_dest:
            with tempfile.NamedTemporaryFile(suffix='.parquet', delete=False) as tmp:
                tmp_path = tmp.name
            try:
                rows_written = write_with_duckdb(query, tmp_path, compression, compression_level,
                                  row_group_size, verbose)
                _report_row_count(rows_written, expect_features)
                upload_to_s3(tmp_path, destination, verbose=progress)
            finally:
                if os.path.exists(tmp_path):
                    os.unlink(tmp_path)
        else:
            rows_written = write_with_duckdb(query, destination, compression, compression_level,
                              row_group_size, verbose)
            _report_row_count(rows_written, expect_features)

        print("✓ CSV point processing completed successfully!")

    except Exception as e:
        print(f"✗ CSV point processing failed: {e}", file=sys.stderr)
        if verbose:
            import traceback
            traceback.print_exc()
        raise
    finally:
        con.close()


def write_with_duckdb(query: str, output_path: str,
                      compression: str = "ZSTD",
                      compression_level: int = 15,
                      row_group_size: int = 100000,
                      verbose: bool = False,
                      row_group_bytes: str = DEFAULT_ROW_GROUP_BYTES,
                      split_dateline: bool = False) -> int:
    """
    Write parquet file using DuckDB COPY. Simple and reliable.

    Returns the number of rows written, which COPY reports for free — the
    caller logs it so a short read is visible in any job log (issue #186).

    Args:
        query: DuckDB query that produces the data to write
        output_path: Local output file path
        compression: Compression algorithm
        compression_level: Compression level
        row_group_size: Rows per group (upper bound on row count)
        row_group_bytes: Upper bound on the uncompressed size of a row group
            (DuckDB ROW_GROUP_SIZE_BYTES). A row group is flushed when EITHER
            this byte budget or row_group_size is reached, so small datasets are
            unaffected while a single huge-geometry column is split into several
            chunks. This is what keeps the geometry column chunk small enough to
            be read over httpfs (issue #106 — see DEFAULT_ROW_GROUP_BYTES).
        verbose: Print debug information
        split_dateline: Register DATELINE_UDF, for a query built with
            wrap_dateline (issue #274).

    Returns:
        Number of rows written to output_path
    """
    con = duckdb.connect(':memory:')
    con.install_extension("spatial")
    con.load_extension("spatial")
    con.execute("SET geometry_always_xy = true")  # (lon, lat) throughout (#280)
    if split_dateline:
        register_dateline_split(con)

    # Enable large buffer size for complex geometries (Total buffer > 2GB)
    con.execute("SET arrow_large_buffer_size=true")

    # The Hilbert sort (issue #276) holds the whole dataset, so cap DuckDB at the
    # pod's budget and let it spill rather than be OOM-killed.
    requested_limit = os.environ.get("DUCKDB_MEMORY_LIMIT")
    if requested_limit:
        con.execute(f"SET memory_limit='{to_duckdb_memory_limit(requested_limit)}'")

    # ROW_GROUP_SIZE_BYTES requires insertion order not to be preserved. That
    # only frees DuckDB to reorder a query without ORDER BY; a spatially
    # ordered query (issue #276) keeps its order.
    con.execute("SET preserve_insertion_order=false")

    try:
        if verbose:
            print(f"  Writing with DuckDB to {output_path}...")
            print(f"    row group cap: {row_group_size:,} rows / {row_group_bytes} bytes")

        # GeoParquet 1.1 with a bbox covering column, so every row group has
        # spatial statistics (Portolan PORTO-FMT-007/012, issue #340). DESCRIBE
        # only binds the query, so the sort below it is not run twice.
        covering = plan_covering(con.execute(f"DESCRIBE ({query})").fetchall())
        geo_options = ""
        extra_kv = None
        if covering is not None:
            # A projection over the ordered query keeps its Hilbert order.
            query = (f'SELECT *, {covering.select} AS "{covering.column}" '
                     f'FROM ({query}) AS _cng_covered')
            # V1 keeps the geometry as plain WKB; the geo key below replaces
            # the 1.0.0 key DuckDB would write.
            geo_options = ",\n             GEOPARQUET_VERSION 'V1'"
            extra_kv = {"geo": json.dumps(covering.geo, separators=(",", ":"))}
            if verbose:
                print(f"    GeoParquet {GEOPARQUET_VERSION}, bbox covering column "
                      f"\"{covering.column}\" on \"{covering.primary}\"")

        # Use COPY - it works!  It also reports how many rows it wrote, which
        # costs nothing extra and is the only count the caller needs: the query
        # is row-preserving, so this is the source feature count as well.
        written = con.execute(f"""
            COPY ({query})
            TO '{output_path}'
            (FORMAT PARQUET,
             COMPRESSION {compression},
             ROW_GROUP_SIZE {row_group_size},
             ROW_GROUP_SIZE_BYTES '{row_group_bytes}'{geo_options}{kv_metadata_sql(extra_kv)})
        """).fetchone()
        rows_written = int(written[0]) if written else 0

        if verbose:
            print(f"  ✓ Wrote {output_path}")

        return rows_written

    finally:
        con.close()



class FeatureCountMismatch(Exception):
    """Raised when the written row count does not match --expect-features."""


def _report_row_count(rows_written: int, expect_features: Optional[int]) -> None:
    """
    Report how many rows were written, and enforce --expect-features.

    A conversion that silently reads a truncated source produces a log
    byte-identical to a complete run, so nothing downstream — human or
    pipeline — can tell (issue #186). The count is always printed; passing an
    independently-known expected count turns a short read into a non-zero exit.

    Args:
        rows_written: Rows COPY reported writing
        expect_features: Row count the caller independently expects, or None
    """
    print(f"  Wrote {rows_written:,} rows")

    if expect_features is None:
        return

    if rows_written != expect_features:
        raise FeatureCountMismatch(
            f"Expected {expect_features:,} features but wrote {rows_written:,} "
            f"({rows_written - expect_features:+,}). The source may be truncated "
            f"or filtered. Nothing further has been done with the output — an S3 "
            f"destination has not been uploaded."
        )
    print(f"  ✓ Matches --expect-features {expect_features:,}")


def upload_to_s3(local_path: str, s3_destination: str, verbose: bool = True) -> None:
    """
    Upload a local file to S3 using rclone.

    Args:
        local_path: Local file path
        s3_destination: S3 destination (s3://bucket/path)
        verbose: Print progress information
    """
    # Convert s3://bucket/path to rclone format nrp:bucket/path
    if not s3_destination.startswith('s3://'):
        raise ValueError(f"S3 destination must start with s3://: {s3_destination}")

    # Parse s3://bucket/path -> nrp:bucket/path
    # The 'nrp' remote is configured in rclone for NRP Nautilus S3
    s3_path = s3_destination[5:]  # Remove s3://
    rclone_dest = f"nrp:{s3_path}"

    if verbose:
        print(f"  Uploading {local_path} to {s3_destination}...")

    result = subprocess.run(
        ['rclone', 'copyto', local_path, rclone_dest, '--progress'],
        capture_output=not verbose,
        text=True
    )

    if result.returncode != 0:
        raise RuntimeError(f"rclone upload failed: {result.stderr if result.stderr else 'Unknown error'}")

    if verbose:
        print(f"  ✓ Uploaded to {s3_destination}")


[docs] def convert_to_parquet( source_url: Union[str, List[str]], destination: str, compression: str = "ZSTD", compression_level: int = 15, row_group_size: int = 100000, geometry_encoding: str = "WKB", id_column: Optional[str] = None, force_id: bool = True, progress: bool = True, target_crs: str = "EPSG:4326", layer: Optional[str] = None, verbose: bool = False, simplify_tolerance: Optional[float] = None, lat_column: Optional[str] = None, lon_column: Optional[str] = None, trim_strings: bool = False, expect_features: Optional[int] = None, csv_sample_size: int = -1, spatial_order: bool = True, ): """ Convert a vector dataset to optimized GeoParquet. Workflow: 1. Detect source CRS using GDAL 2. Check if ID column exists or needs creation 3. Build DuckDB query to read, add ID, and reproject 4. Write GeoParquet with DuckDB COPY 5. Upload to S3 via rclone if destination is S3 Args: source_url: Source dataset URL or list of URLs (supports s3://, http://, file paths). Multiple URLs will be merged with UNION ALL. destination: Output path (s3:// or local file path) compression: Compression algorithm (ZSTD, GZIP, SNAPPY, NONE) compression_level: Compression level (1-22 for ZSTD) row_group_size: Number of rows per group geometry_encoding: Geometry encoding (WKB, WKT) id_column: Specific ID column to use (auto-detected if not specified) force_id: Create _cng_fid if no suitable ID column exists progress: Show progress during conversion target_crs: Target CRS for output (default: EPSG:4326). The source is reprojected whenever its own CRS differs, including when that CRS carries no EPSG or authority code and is only available as a WKT definition (issue #187). A source that declares no CRS at all is assumed to be in target_crs already and written unchanged. layer: Layer name for multi-layer datasets (e.g., GDB) verbose: Print detailed debug information simplify_tolerance: Optional geometry simplification tolerance in target-CRS units (e.g. degrees for EPSG:4326), applied after reprojection via ST_SimplifyPreserveTopology (issue #132) lat_column: Latitude column name for CSV point input (auto-detected if not given, issue #78) lon_column: Longitude column name for CSV point input (auto-detected if not given, issue #78) trim_strings: Strip leading/trailing whitespace from every string (VARCHAR) attribute column. Off by default so outputs stay faithful to the source; opt in for sources whose categorical fields carry stray whitespace (e.g. WDPA NO_TAKE = 'All ', issue #180). expect_features: Row count this conversion is expected to produce, known independently by the caller (issue #186). The count is always logged; when this is given and the written count differs, the conversion raises FeatureCountMismatch so a pipeline can gate on it. csv_sample_size: For CSV point sources, rows read_csv_auto samples for type inference; -1 (the default) scans the whole file (issue #188). spatial_order: Write rows in Hilbert order of their geometry and number a synthetic _cng_fid in that order (issue #276). Turn off to keep source order, e.g. when the sort will not fit the pod. """ # CSV with lat/lon columns -> point geometry (issue #78). Handled before the # ST_Read path since CSV is not a spatial format GDAL/ST_Read opens directly. if not isinstance(source_url, list) and is_csv_file(source_url): return process_csv_input( source_url=source_url, destination=destination, lat_column=lat_column, lon_column=lon_column, compression=compression, compression_level=compression_level, row_group_size=row_group_size, id_column=id_column, force_id=force_id, progress=progress, target_crs=target_crs, verbose=verbose, trim_strings=trim_strings, expect_features=expect_features, csv_sample_size=csv_sample_size, spatial_order=spatial_order, ) # Check if input is already parquet # Handle list of sources vs single source if isinstance(source_url, list): # Multiple sources provided - handle below is_multi_source = True source_urls = source_url # Use first URL for metadata detection representative_source = source_urls[0] else: is_multi_source = False source_urls = [source_url] representative_source = source_url # Check if all inputs are parquet (special handling) if all(is_parquet_file(url) for url in source_urls): # Use parquet-specific processing (no ST_Read) # Note: currently only supports single parquet input if is_multi_source: raise ValueError("Multiple parquet inputs not yet supported. Please merge them first or use vector formats.") return process_parquet_input( source_url=source_urls[0], destination=destination, compression=compression, compression_level=compression_level, row_group_size=row_group_size, id_column=id_column, force_id=force_id, progress=progress, target_crs=target_crs, verbose=verbose, simplify_tolerance=simplify_tolerance, trim_strings=trim_strings, expect_features=expect_features, spatial_order=spatial_order, ) # Original processing for non-parquet inputs if is_multi_source: print(f"Converting {len(source_urls)} sources:") for i, url in enumerate(source_urls, 1): print(f" {i}. {url}") else: print(f"Converting {source_urls[0]}") if layer: print(f" layer {layer}") print(f" to {destination}") if progress: print(f" Compression: {compression} level {compression_level}") print(f" Row group size: {row_group_size:,}") # Check if any source is a .zip file has_zip = any(url.lower().endswith(".zip") for url in source_urls) if has_zip and is_multi_source: raise ValueError("Cannot mix .zip files with multiple source URLs. Extract zip files or process separately.") is_zip = source_urls[0].lower().endswith(".zip") if not is_multi_source else False if is_zip: # Strip GDAL VSI prefixes if present so we can download the raw file if source_urls[0].startswith('/vsicurl/'): source_urls[0] = source_urls[0].replace('/vsicurl/', '') try: temp_dir = None linearize_dir = None localize_dirs = [] source_inputs = [] if is_zip: print(f" Detected Zip archive: {source_urls[0]}") temp_dir = tempfile.mkdtemp() print(f" Created temporary directory: {temp_dir}") download_and_extract(source_urls[0], temp_dir, verbose=verbose) source_inputs = find_vector_sources(temp_dir) if not source_inputs: raise ValueError("No vector sources (.shp, .gdb, .gpkg, .fgb) found in zip archive") print(f" Found {len(source_inputs)} vector source(s) in archive") # Use the first source as representative for metadata representative_source = source_inputs[0] print(f" Using {os.path.basename(representative_source)} for metadata detection") elif is_multi_source: # Multiple non-zip sources print(f" Processing {len(source_urls)} input files...") processed_sources = [] for url in source_urls: # A remote .gdb is a directory GDAL cannot open over s3://; # localize it to disk first (issue #152). Other remote sources # are rewritten to GDAL /vsicurl paths (issue #153). localized, gdb_dir = _localize_gdb(url, verbose=verbose) if gdb_dir: localize_dirs.append(gdb_dir) processed_sources.append(localized) else: processed_sources.append(to_gdal_readable(url)) source_inputs = processed_sources representative_source = processed_sources[0] else: # Single non-zip source # A remote .gdb is a directory GDAL cannot open over s3://; localize # it to disk first (issue #152). Other remote sources are rewritten # to GDAL /vsicurl paths so ST_Read can open them (issue #153). localized, gdb_dir = _localize_gdb(source_urls[0], verbose=verbose) if gdb_dir: localize_dirs.append(gdb_dir) source_urls[0] = localized else: source_urls[0] = to_gdal_readable(source_urls[0]) source_inputs = source_urls[0] representative_source = source_urls[0] # Step 0b: Narrow to the requested layer and refuse unions that cannot # work, before anything calls ST_Read — which segfaults on a layer its # source does not have (issue #216). if isinstance(source_inputs, list): if layer and not is_zip: # Sources named explicitly: each must have the layer. Dropping # one the caller listed would be a silent change of input. for src in source_inputs: require_layer(src, layer) elif layer: # An archive's contents were not chosen by the caller, so # narrow them to the sources that hold the layer. chosen = select_sources_for_layer(source_inputs, layer) if len(chosen) < len(source_inputs): names = ", ".join(os.path.basename(c.rstrip("/")) for c in chosen) print(f" --layer {layer}: using {len(chosen)} of " f"{len(source_inputs)} source(s): {names}") source_inputs = chosen representative_source = chosen[0] if len(source_inputs) > 1: check_union_compatible(source_inputs, layer) elif layer: require_layer(source_inputs, layer) # Step 1: Detect source CRS and geometry column print(" Detecting source CRS...") detected = detect_crs(representative_source, layer=layer, verbose=verbose) source_crs = detected.crs print(" Detecting geometry column...") geom_col, geom_is_blob = get_geometry_column(representative_source, layer=layer, verbose=verbose) print(f" Geometry column: {geom_col}" + (" (BLOB — will cast via ST_GeomFromWKB)" if geom_is_blob else "")) needs_reprojection = False if source_crs: if source_crs != target_crs: if detected.kind == "definition": # The WKT itself is long and unreadable in a log line; name # the CRS and say where the definition came from instead. print(f" Source CRS: {detected.detail} (no EPSG or authority code — " f"reprojecting from its full definition)") print(f" -> Reprojecting to {target_crs}") else: print(f" Source CRS: {source_crs} -> Reprojecting to {target_crs}") needs_reprojection = True else: print(f" Source already in {target_crs}") elif detected.kind == "undetectable": # Not the same as a dataset that declares no CRS: something went # wrong reading this one, so the assumption below is a guess made on # no evidence. Say so at normal verbosity — the output is tagged # {target_crs} either way, and nothing downstream can tell. print(f" ⚠ Could not read the source CRS: {detected.detail}") print(f" Assuming the data is already in {target_crs} and writing it unchanged.") print(f" If it is not, the output will carry {target_crs} metadata over coordinates") print(" in some other system. Reproject first (ogr2ogr -t_srs) if unsure.") else: print(f" Warning: dataset declares no CRS, assuming {target_crs}") # Step 1b: Linearize curved geometries if needed (e.g., MULTISURFACE -> MULTIPOLYGON) linearized_source, effective_layer, linearize_dir = _linearize_source( representative_source, layer=layer, verbose=verbose ) if linearize_dir: # Source was linearized to a temp GPKG — update references source_inputs = linearized_source representative_source = linearized_source layer = effective_layer # Re-detect geometry column for the linearized file geom_col, geom_is_blob = get_geometry_column(linearized_source, layer=effective_layer, verbose=verbose) print(f" Geometry column (linearized): {geom_col}") # Step 1c: Flatten measured/3D (M/Z) geometries to 2D. # DuckDB stores M/Z geometry as BLOB rather than GEOMETRY, which silently # breaks reprojection and all downstream steps. Pre-process with ogr2ogr # -dim XY so DuckDB sees a standard 2D GEOMETRY column. flatten_dir = None if _has_non_2d_geometry(representative_source, layer=layer): flattened_source, flat_layer, flatten_dir = _flatten_to_2d( source_inputs, layer=layer, verbose=verbose ) if flatten_dir: source_inputs = flattened_source representative_source = flattened_source layer = flat_layer geom_col, geom_is_blob = get_geometry_column(flattened_source, layer=flat_layer, verbose=verbose) print(f" Geometry column (flattened): {geom_col}") # Step 1d: List string columns to trim (issue #180). Detected on the # representative source; a UNION ALL of multiple sources is positional # and already requires matching schemas, so one probe covers them all. trim_columns = None if trim_strings: trim_columns = get_string_columns(representative_source, layer=layer, verbose=verbose) print(f" Trimming whitespace from {len(trim_columns)} string column(s)") # Step 2: Build read/reproject query print(" Building read/reproject query...") split_dateline = needs_reprojection and is_geographic_target(target_crs) query = build_read_reproject_query( source_inputs, source_crs if needs_reprojection else None, target_crs, geom_col=geom_col, layer=layer, verbose=verbose, geom_is_blob=geom_is_blob, simplify_tolerance=simplify_tolerance, trim_columns=trim_columns, wrap_dateline=split_dateline, ) # Step 3: Check ID column and wrap query if needed print(" Checking for ID column...") needs_id, id_col_name = check_id_column(representative_source, layer=layer, id_column=id_column, force_id=force_id, verbose=verbose) if needs_id: print(f" Adding synthetic ID column: {id_col_name}") else: print(f" Using existing ID column: {id_col_name}") if spatial_order: # A source with no readable CRS may hold any coordinates, so its # curve spans its own extent rather than the lon/lat plane. geographic = source_crs is not None and is_geographic_target(target_crs) print(" Ordering rows along a Hilbert curve" + (f" and numbering {id_col_name} in that order" if needs_id else "")) query = spatial_order_query(query, geom_col, id_col_name if needs_id else None, geographic=geographic) elif needs_id: query = add_id_column_query(query, id_col_name) # Step 4: Write with DuckDB is_s3_dest = destination.startswith('s3://') if is_s3_dest: # Write to temp file first with tempfile.NamedTemporaryFile(suffix='.parquet', delete=False) as tmp: tmp_path = tmp.name try: # Write data rows_written = write_with_duckdb(query, tmp_path, compression, compression_level, row_group_size, verbose, split_dateline=split_dateline) # Checked before the upload, so a short read never reaches the # bucket to be consumed by anything downstream (issue #186). _report_row_count(rows_written, expect_features) # Upload to S3 upload_to_s3(tmp_path, destination, verbose=progress) finally: if os.path.exists(tmp_path): os.unlink(tmp_path) else: # Write directly to destination rows_written = write_with_duckdb(query, destination, compression, compression_level, row_group_size, verbose, split_dateline=split_dateline) _report_row_count(rows_written, expect_features) if verbose: print("✓ Conversion completed successfully!") except Exception as e: print(f"✗ Conversion failed: {e}", file=sys.stderr) if verbose: import traceback traceback.print_exc() raise finally: if 'linearize_dir' in locals() and linearize_dir and os.path.exists(linearize_dir): if verbose: print(f" Cleaning up linearization temp dir: {linearize_dir}") shutil.rmtree(linearize_dir, ignore_errors=True) if 'flatten_dir' in locals() and flatten_dir and os.path.exists(flatten_dir): if verbose: print(f" Cleaning up flatten temp dir: {flatten_dir}") shutil.rmtree(flatten_dir, ignore_errors=True) if 'temp_dir' in locals() and temp_dir and os.path.exists(temp_dir): if verbose: print(f" Cleaning up temporary directory: {temp_dir}") shutil.rmtree(temp_dir) if 'localize_dirs' in locals(): for d in localize_dirs: if d and os.path.exists(d): if verbose: print(f" Cleaning up localized GDB temp dir: {d}") shutil.rmtree(d, ignore_errors=True)
def main(): """CLI entry point.""" parser = argparse.ArgumentParser( description="Convert vector datasets to optimized GeoParquet format", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" Examples: # Convert local shapefile cng-convert-to-parquet input.shp output.parquet # Convert from S3 to S3 cng-convert-to-parquet s3://bucket/input.shp s3://bucket/output.parquet # Convert with custom compression cng-convert-to-parquet input.shp output.parquet --compression GZIP --compression-level 9 # Convert and specify ID column cng-convert-to-parquet input.shp output.parquet --id-column objectid # Convert a GDB layer, trimming whitespace from string attributes cng-convert-to-parquet WDPA.gdb wdpa.parquet --layer WDPA_poly --trim-strings """ ) parser.add_argument("source", nargs='+', help="Source dataset URL(s) or path(s). Multiple sources will be merged with UNION ALL.") parser.add_argument("destination", help="Output GeoParquet path") parser.add_argument("--compression", default="ZSTD", choices=["ZSTD", "GZIP", "SNAPPY", "NONE"], help="Compression algorithm (default: ZSTD)") parser.add_argument("--compression-level", type=int, default=15, help="Compression level (default: 15 for ZSTD)") parser.add_argument("--row-group-size", type=int, default=100000, help="Rows per group (default: 100000)") parser.add_argument("--geometry-encoding", default="WKB", choices=["WKB", "WKT"], help="Geometry encoding (default: WKB)") parser.add_argument("--id-column", help="ID column name (auto-detected if not specified)") parser.add_argument("--no-force-id", action="store_true", help="Don't create synthetic ID if none exists") parser.add_argument("--target-crs", default="EPSG:4326", help="Target CRS (default: EPSG:4326)") parser.add_argument("--simplify-tolerance", type=float, default=None, help="Simplify geometry to this tolerance in TARGET-CRS units " "(degrees for EPSG:4326; e.g. 0.0001 ~ 10 m at the equator) " "via ST_SimplifyPreserveTopology, applied after reprojection. " "Right-sizes high-vertex sources for tiling/hex.") parser.add_argument("--trim-strings", action="store_true", help="Strip leading/trailing whitespace (spaces, tabs, newlines) " "from every string column. Off by default: conversion stays " "faithful to the source. Opt in for sources whose categorical " "fields carry stray whitespace, which silently breaks equality " "filters (e.g. WDPA NO_TAKE = 'All ' vs 'All').") parser.add_argument("--layer", help="Layer name for multi-layer datasets (e.g., GDB files)") parser.add_argument("--lat-column", default=None, help="Latitude column for CSV point input (auto-detected from " "e.g. Latitude/lat/y if not given). Issue #78.") parser.add_argument("--lon-column", default=None, help="Longitude column for CSV point input (auto-detected from " "e.g. Longitude/lon/x if not given). Issue #78.") parser.add_argument("--expect-features", type=int, default=None, metavar="N", help="Row count this conversion is expected to produce, known " "independently (e.g. from the source service's own count). " "Exits non-zero when the written count differs, so a " "silently truncated source is caught rather than published. " "The count is logged either way. Issue #186.") parser.add_argument("--csv-sample-size", type=int, default=-1, metavar="ROWS", help="Rows sampled for CSV type inference (default: -1, the whole " "file). DuckDB's 20480-row default types a column that is " "empty in the head of the file as VARCHAR even when it is " "cleanly numeric later on. Issue #188.") parser.add_argument("--no-spatial-order", dest="spatial_order", action="store_false", help="Keep source row order instead of writing rows in Hilbert " "order of their geometry, with _cng_fid numbered in that " "order. Use it when the sort does not fit the pod. Issue #276.") parser.add_argument("--no-progress", action="store_true", help="Disable progress output") parser.add_argument("--verbose", action="store_true", help="Enable detailed debug output") args = parser.parse_args() # Handle single vs multiple sources source_inputs = args.source if len(args.source) > 1 else args.source[0] try: convert_to_parquet( source_url=source_inputs, destination=args.destination, compression=args.compression, compression_level=args.compression_level, row_group_size=args.row_group_size, geometry_encoding=args.geometry_encoding, id_column=args.id_column, force_id=not args.no_force_id, progress=not args.no_progress, target_crs=args.target_crs, layer=args.layer, verbose=args.verbose, simplify_tolerance=args.simplify_tolerance, lat_column=args.lat_column, lon_column=args.lon_column, trim_strings=args.trim_strings, expect_features=args.expect_features, csv_sample_size=args.csv_sample_size, spatial_order=args.spatial_order, ) sys.exit(0) except Exception as e: print(f"Error: {e}", file=sys.stderr) sys.exit(1) if __name__ == "__main__": main()