"""Helpers to transform Pandas time-series data into baseline ECharts options dictionaries, while still allowing user customisation."""

# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/01_helpers.ipynb.

# %% ../nbs/01_helpers.ipynb #e3ec8e75
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING: import pandas as pd

# %% auto #0
__all__ = ['ts_options']

# %% ../nbs/01_helpers.ipynb #860adb14
def ts_options(data: pd.DataFrame | pd.Series, x: str = None, y: list | str = None, kind: str = "line") -> dict:
    """
    Transforms a Pandas DataFrame or Series into a baseline ECharts time-series options dictionary.
    """
    import pandas as pd

    # 1. Handle Pandas Series gracefully
    if isinstance(data, pd.Series):
        # Give it a default name if it lacks one, so it can be used as a y-column
        name = data.name if data.name is not None else "value"
        plot_df = data.to_frame(name=name)
    else:
        plot_df = data.copy()

    # 2. Handle the X-axis (Time)
    if x is None:
        # Fall back to the index if no x column is provided
        x = plot_df.index.name or "date"
        plot_df.index.name = x
        plot_df = plot_df.reset_index()
    
    # Format datetimes safely to ISO 8601 while PRESERVING timezone offsets
    if pd.api.types.is_datetime64_any_dtype(plot_df[x]):
        plot_df[x] = plot_df[x].apply(lambda dt: dt.isoformat() if pd.notnull(dt) else None)

    # 3. Handle the Y-axis (Values)
    if y is None:
        # Default to all numeric columns except the time column
        y = plot_df.select_dtypes(include='number').columns.tolist()
        if x in y: y.remove(x)
    elif isinstance(y, str):
        y = [y]

    # 4. Handle NaNs cleanly (Convert to None for JSON `null`)
    # Converting to object dtype first prevents Pandas from trying to force NaNs back into floats
    plot_df = plot_df[[x] + y].astype(object).where(pd.notna(plot_df), None)

    # 5. Construct the ECharts Dataset
    headers = [x] + y
    dataset_source = [headers] + plot_df.values.tolist()

    # 6. Build the baseline ECharts dictionary
    options = {
        "dataset": {
            "source": dataset_source
        },
        "tooltip": {
            "trigger": "axis"
        },
        "xAxis": {
            "type": "time", 
            "name": str(x)
        },
        "yAxis": {
            "type": "value"
        },
        "series": [
            {
                "type": kind, 
                "name": str(col), 
                "encode": {"x": str(x), "y": str(col)}
            } 
            for col in y
        ]
    }

    return options
