"""
Retrieve weather for the period from 1950 till 2100
Select days with maximum and minimum features
"""
from datetime import datetime
from pathlib import Path

from drias.climate import fetch_climate

# get weather 150 years
df = fetch_climate(latitude=43.520199,
                   longitude=5.647930,
                   scenario="med",
                   date_beg=datetime(1950, 1, 1),
                   date_end=datetime(2099, 12, 31))

df = df.rename(columns={
    'maxTemperature': 'tmax',
    'minTemperature': 'tmin',
    'meanTemperature': 'tmean',
    'relativeHumidity': 'rh',
    'solarRadiation': 'rg',
    'totalPrecipitation': 'rain',
    'windSpeed': 'ws'})

# extract days with minimum or maximum values
extrema = set(df.idxmin()) | set(df.idxmax())

df_extrema = df.loc[extrema].sort_index().sort_index(axis=1)

# write resulting dataframe
with open(Path(__file__).parent / "climate.csv", 'w', encoding="utf8") as fhw:
    fhw.write(f"# This file has been generated by {__file__}\n#\n")
    fhw.write("# rain: [mm] total precipitation for the day\n")
    fhw.write("# rg: [J cm-2] solar radiation\n")
    fhw.write("# rh: [-] relative humidity between 0 and 1\n")
    fhw.write("# tmax: [°C] maximum temperature for a day\n")
    fhw.write("# tmean: [°C] mean temperature for a day\n")
    fhw.write("# tmin: [°C] minimum temperature for a day\n")
    fhw.write("# ws: [m s-1] mean wind speed\n")
    fhw.write("#\n")
    df_extrema.to_csv(fhw, sep=";")
