"""Date parsing, Polars helpers, and batching logic utilities."""

from datetime import date, datetime

from yarl import URL

DATE_FORMATTER = "%Y-%m-%d"

# API Base URLs
DATA_API_URL = URL("https://data-dev.api.yukkalab.com/9-3-5/2023-12-13-0/")
METADATA_API_URL = URL("https://metadata.api.yukkalab.com/")

type IntoDateTime = str | datetime | date | float


def to_datetime(d: IntoDateTime) -> datetime:
    """Convert various date/time types to datetime.

    Args:
        d: Input date/time in various formats:
            - str: ISO format or DATE_FORMATTER format (%Y-%m-%d)
            - datetime: Passed through unchanged
            - date: Converted to datetime at midnight
            - float: Interpreted as Unix timestamp

    Returns:
        Datetime object

    Raises:
        TypeError: If input type is not supported
        ValueError: If string format is invalid
    """
    match d:
        case datetime():
            return d
        case date():
            return datetime(year=d.year, month=d.month, day=d.day, hour=0, minute=0, second=0)
        case float():
            return datetime.fromtimestamp(d)
        case str():
            try:
                return datetime.strptime(d, DATE_FORMATTER)
            except ValueError:
                try:
                    return datetime.fromisoformat(d)
                except ValueError as e:
                    raise ValueError(f"Invalid isoformat date string: {d!r}") from e
    raise TypeError(f"Type {type(d)} not supported")
