from __future__ import annotations

from datetime import date
from typing import Any, Optional

import dask.dataframe as dd


from sibi_flux.dask_cluster.core import safe_compute, safe_persist


def is_dask_df(x: Any) -> bool:
    return isinstance(x, dd.DataFrame)


def maybe_persist(df: Any, persist: bool):
    return safe_persist(df) if persist and is_dask_df(df) else df


def maybe_compute(df: Any, as_pandas: bool):
    return safe_compute(df) if as_pandas and is_dask_df(df) else df


def parse_iso_date(value: Optional[str], field_name: str) -> Optional[date]:
    if value is None:
        return None
    if not isinstance(value, str):
        raise TypeError(f"{field_name} must be a string in YYYY-MM-DD format.")
    try:
        return date.fromisoformat(value)
    except ValueError as e:
        raise ValueError(f"{field_name} must be in YYYY-MM-DD format.") from e
