"""Shared date/timezone utility functions."""

from __future__ import annotations

import pandas as pd

from dyfinance._constants import CACHEABLE_INTERVALS


def normalize_index(index: pd.DatetimeIndex, interval: str) -> pd.DatetimeIndex:
    """Normalize timestamps for cache storage.

    Daily+ intervals: use trading date as UTC midnight (time is meaningless).
    Intraday intervals: convert to UTC preserving time.
    """
    if interval in CACHEABLE_INTERVALS:
        return pd.DatetimeIndex(index.date, tz="UTC")
    return ensure_utc_index(index)


def ensure_utc_index(index: pd.DatetimeIndex) -> pd.DatetimeIndex:
    """Ensure a DatetimeIndex is UTC-localized.

    If tz-naive, localize to UTC. If tz-aware, convert to UTC.
    """
    if index.tz is None:
        return index.tz_localize("UTC")
    return index.tz_convert("UTC")
