#!/usr/bin/env python3
"""CRS helpers."""

import math

from pyproj import CRS


def determine_utm_crs(geometry):
    """
    Determine an appropriate WGS84 UTM CRS for the given geometry.

    Uses the centroid of the geometry's bounding box in EPSG:4326 to choose
    a UTM zone, returning the corresponding CRS (EPSG:326xx for the northern
    hemisphere and EPSG:327xx for the southern hemisphere).
    """
    if geometry.crs is None:
        raise ValueError("Geometry lacks CRS; cannot determine UTM zone.")

    wgs84 = geometry.to_crs(epsg=4326) if geometry.crs.to_epsg() != 4326 else geometry
    minx, miny, maxx, maxy = wgs84.total_bounds
    center_lon = (minx + maxx) / 2.0
    center_lat = (miny + maxy) / 2.0

    zone = int(math.floor((center_lon + 180) / 6) + 1)
    zone = max(1, min(zone, 60))
    north = center_lat >= 0
    epsg_code = 32600 + zone if north else 32700 + zone
    return CRS.from_epsg(epsg_code)
