import xarray as xr
import pandas as pd

def monthly2seasonal(ds: xr.Dataset, nmonths: int = 3) -> xr.Dataset:
    # Sort by time and create a complete monthly time series
    ds = ds.sortby("time")
    start, end = ds.time.to_index()[[0, -1]]
    new_time_index = pd.date_range(start=f"{start.year}-01-01", 
                                    end=f"{end.year}-12-31", 
                                    freq="MS")
    
    # Reindex, compute seasonal means, and trim to original time range
    return (ds.reindex(time=new_time_index)
            .rolling(time=nmonths, center=True).mean()
            .sel(time=slice(start, end))
            .dropna(dim="time"))