"""
Parse TSWCs from CSV
======================

This example shows how to parse a Time Series Wind Climate (TSWC) from a .csv file.

"""

# %%
# Prepare Sample Data
# ------------------------
# First, we need to prepare the sample data. This is done by creating a
# DataFrame with the wind speed and direction data.

import tempfile
from pathlib import Path

import numpy as np
import pandas as pd
import windkit as wk


size = 8760  # 1 year of hourly data

df = pd.DataFrame(
    {
        "wspd_50": np.random.uniform(5, 15, size=size),  # Wind speed in m/s
        "wdir_50": np.random.uniform(0, 360, size=size),  # Wind direction in degrees
    },
    index=pd.date_range("2023-01-01", periods=size, freq="h"),
)
df.index.name = "time"  # Set the index name to 'time'
print(df.head())

# %%
# Save to .csv
# ------------------------
# We save the DataFrame to a .csv file in a temporary directory.

tmpdir = tempfile.TemporaryDirectory()
csv_path = Path(tmpdir.name) / "sample_tswc.csv"
df.to_csv(csv_path, index=True)

# %%
# Parse .csv to TSWC
# ------------------------
# Now, we can parse the CSV file to create a Time Series Wind Climate (TSWC) object using
# the :py:func:`windkit.read_tswc` function. We have to specify the spatial coordinate system (CRS),
# coordinates for the west-east and south-north axes,
# the time column, and the height to columns mapping. In this case, we assume that the
# wind speed and direction data are at a height of 50 meters, and we map them accordingly.

tswc = wk.read_tswc(
    csv_path,
    west_east=0.0,
    south_north=0.0,
    crs=4326,
    time_col=0,
    height_to_columns={50: ["wspd_50", "wdir_50"]},
)

print(tswc)

# %%
# Alternatively, we can also use the :py:func:`windkit.tswc_from_dataframe` function to parse a
# DataFrame directly into a TSWC object. This is useful if you already have the data in a
# DataFrame format and do not need to read it from a file.

tswc_from_df = wk.tswc_from_dataframe(
    df,
    west_east=0.0,
    south_north=0.0,
    crs=4326,
    height_to_columns={50: ["wspd_50", "wdir_50"]},
)
print(tswc_from_df)

tmpdir.cleanup()
