import numpy as np
import pandas as pd

def uv2df(u, v):
    """Wind components → (speed m/s, direction degrees). Matches Fortran uv2df.
    Works on arrays of any shape.
    """

    zsmall = 0.001  # same constant from Fortran

    abs_u = np.abs(u)
    abs_v = np.abs(v)

    V = np.where(abs_u > zsmall, np.hypot(u, v),
                 np.where(abs_v > zsmall, abs_v, 0.0))

    # Avoid division by zero in arctan branch
    safe_u = np.where(abs_u > zsmall, u, 1.0)

    dd = np.where(abs_u > zsmall,
                  180.0 + (np.sign(u) * 90.0) - np.arctan(v / safe_u) * 57.2957795, # 180/pi
                  np.where(abs_v > zsmall,
                           270.0 - (np.sign(v) * 90.0),
                           0.0))
    return V, dd

def nint(arr): # exactly fortran nint(), np.round() can make rounding errors
    return np.floor(np.abs(arr) + 0.5) * np.sign(arr)


def select_period_bounds(datestamp):
    """"
    # Season 1 (winter):         Sep 21 – Mar 20
    # Season 2 (spring/autumn):  Mar 21 – Apr 20  and  Aug 21 – Sep 20
    # Season 3 (summer):         Apr 21 – Aug 20
    """
    nm = datestamp.month
    nd = datestamp.day
    if nm < 3 or (nm == 3 and nd < 21) or nm > 9 or (nm == 9 and nd >= 21):
        return "winter"  
    elif (nm == 3 and nd >= 21) or (nm == 4 and nd < 21) \
            or (nm == 8 and nd >= 21) or (nm == 9 and nd < 21):
        return "spring_autumn"  
    else:
        return "summer" 