"""Runtime compatibility fixes for the Pathfinder ILAMB 2.7 environment.

Python imports ``sitecustomize`` automatically when this directory is placed
on ``PYTHONPATH``. Keep the patch narrowly scoped so it cannot alter non-global
or non-Robinson plots.
"""

from __future__ import annotations

import cartopy.crs as ccrs
from cartopy.mpl.geoaxes import GeoAxes


_ORIGINAL_SET_EXTENT = GeoAxes.set_extent


def _set_extent_with_global_robinson_fallback(self, extents=None, crs=None):
    """Use ``set_global`` for the Cartopy 0.25/Matplotlib 3.11 pole bug."""
    try:
        return _ORIGINAL_SET_EXTENT(self, extents, crs=crs)
    except ValueError as exc:
        values = list(extents) if extents is not None else []
        is_global = (
            len(values) == 4
            and values[0] <= -180
            and values[1] >= 180
            and values[2] <= -90
            and values[3] >= 90
        )
        if (
            str(exc) == "Axis limits cannot be NaN or Inf"
            and isinstance(self.projection, ccrs.Robinson)
            and is_global
        ):
            return self.set_global()
        raise


if not getattr(GeoAxes.set_extent, "_ilamb_global_fallback", False):
    _set_extent_with_global_robinson_fallback._ilamb_global_fallback = True
    GeoAxes.set_extent = _set_extent_with_global_robinson_fallback
