from __future__ import annotations

from collections.abc import Iterable
from typing import Any

from flownet.core.types import PayloadData


class ResultNormalizer:
    """Normalize operator results into PayloadData lists."""

    def normalize(self, result: Any, expand_iterable: bool) -> list[PayloadData]:
        if result is None:
            return []

        if isinstance(result, PayloadData):
            return [result]

        if isinstance(result, list) and all(
            isinstance(item, PayloadData) for item in result
        ):
            return result

        if isinstance(result, (str, bytes)):
            return [PayloadData(args=[result], kwargs={})]

        if expand_iterable and isinstance(result, Iterable):
            payloads: list[PayloadData] = []
            for item in result:
                if isinstance(item, PayloadData):
                    payloads.append(item)
                else:
                    payloads.append(PayloadData(args=[item], kwargs={}))
            return payloads

        return [PayloadData(args=[result], kwargs={})]


__all__ = ["ResultNormalizer"]
