"""
Description of grid used by most weather models

https://confluence.ecmwf.int/display/CKB/ERA5%3A+What+is+the+spatial+reference
https://cds.climate.copernicus.eu/datasets/reanalysis-era5-single-levels?tab=overview

Grid of 0.25°x0.25° in latitude x longitude
"""

res_lat = 0.25  # [°] see header
res_long = 0.25  # [°] see header


def closest_ref(latitude, longitude):
    """Closest point on era5 grid

    Args:
        latitude (float): [deg] latitude
        longitude (float): [deg] longitude

    Returns:
        (float, float): [deg]
    """
    ref_lat = int((90 + latitude) / res_lat + 0.5) * res_lat - 90
    ref_long = int((180 + longitude) / res_long + 0.5) * res_long - 180

    return ref_lat, ref_long


def latitude_ref(latitude):
    """Latitude of reference points around latitude

    Args:
        latitude (float): [deg] latitude

    Returns:
        (float, float): [deg]
    """
    lat_min = int((90 + latitude) / res_lat) * res_lat - 90
    lat_max = int(latitude / res_lat + 1) * res_lat
    return lat_min, lat_max


def longitude_ref(longitude):
    """Longitude of reference points around longitude

    Args:
        longitude (float): [deg] longitude

    Returns:
        (float, float): [deg]
    """
    long_min = int((180 + longitude) / res_long) * res_long - 180
    long_max = int(longitude / res_long + 1) * res_long
    return long_min, long_max
