import copy
import functools
import warnings
from types import MethodType
from typing import Dict, List, Optional, Type, Union

import dill
import pandas as pd

from feast.base_feature_view import BaseFeatureView
from feast.data_source import RequestSource
from feast.errors import RegistryInferenceFailure, SpecifiedFeaturesNotPresentError
from feast.feature import Feature
from feast.feature_view import FeatureView
from feast.feature_view_projection import FeatureViewProjection
from feast.field import Field, from_value_type
from feast.protos.feast.core.OnDemandFeatureView_pb2 import (
    OnDemandFeatureView as OnDemandFeatureViewProto,
)
from feast.protos.feast.core.OnDemandFeatureView_pb2 import (
    OnDemandFeatureViewMeta,
    OnDemandFeatureViewSpec,
    OnDemandSource,
)
from feast.protos.feast.core.OnDemandFeatureView_pb2 import (
    UserDefinedFunction as UserDefinedFunctionProto,
)
from feast.type_map import (
    feast_value_type_to_pandas_type,
    python_type_to_feast_value_type,
)
from feast.usage import log_exceptions
from feast.value_type import ValueType

warnings.simplefilter("once", DeprecationWarning)


class OnDemandFeatureView(BaseFeatureView):
    """
    [Experimental] An OnDemandFeatureView defines a logical group of features that are
    generated by applying a transformation on a set of input sources, such as feature
    views and request data sources.

    Attributes:
        name: The unique name of the on demand feature view.
        features: The list of features in the output of the on demand feature view.
        source_feature_view_projections: A map from input source names to actual input
            sources with type FeatureViewProjection.
        source_request_sources: A map from input source names to the actual input
            sources with type RequestSource.
        udf: The user defined transformation function, which must take pandas dataframes
            as inputs.
        description: A human-readable description.
        tags: A dictionary of key-value pairs to store arbitrary metadata.
        owner: The owner of the on demand feature view, typically the email of the primary
            maintainer.
    """

    # TODO(adchia): remove inputs from proto and declaration
    name: str
    features: List[Field]
    source_feature_view_projections: Dict[str, FeatureViewProjection]
    source_request_sources: Dict[str, RequestSource]
    udf: MethodType
    description: str
    tags: Dict[str, str]
    owner: str

    @log_exceptions
    def __init__(
        self,
        *args,
        name: Optional[str] = None,
        features: Optional[List[Feature]] = None,
        sources: Optional[
            Dict[str, Union[FeatureView, FeatureViewProjection, RequestSource]]
        ] = None,
        udf: Optional[MethodType] = None,
        inputs: Optional[
            Dict[str, Union[FeatureView, FeatureViewProjection, RequestSource]]
        ] = None,
        schema: Optional[List[Field]] = None,
        description: str = "",
        tags: Optional[Dict[str, str]] = None,
        owner: str = "",
    ):
        """
        Creates an OnDemandFeatureView object.

        Args:
            name: The unique name of the on demand feature view.
            features (deprecated): The list of features in the output of the on demand
                feature view, after the transformation has been applied.
            sources (optional): A map from input source names to the actual input sources,
                which may be feature views, feature view projections, or request data sources.
                These sources serve as inputs to the udf, which will refer to them by name.
            udf (optional): The user defined transformation function, which must take pandas
                dataframes as inputs.
            inputs (optional): A map from input source names to the actual input sources,
                which may be feature views, feature view projections, or request data sources.
                These sources serve as inputs to the udf, which will refer to them by name.
            schema (optional): The list of features in the output of the on demand feature
                view, after the transformation has been applied.
            description (optional): A human-readable description.
            tags (optional): A dictionary of key-value pairs to store arbitrary metadata.
            owner (optional): The owner of the on demand feature view, typically the email
                of the primary maintainer.
        """
        positional_attributes = ["name", "features", "inputs", "udf"]

        _name = name

        _schema = schema or []
        if len(_schema) == 0 and features is not None:
            _schema = [Field.from_feature(feature) for feature in features]
        if features is not None:
            warnings.warn(
                (
                    "The `features` parameter is being deprecated in favor of the `schema` parameter. "
                    "Please switch from using `features` to `schema`. This will also requiring switching "
                    "feature definitions from using `Feature` to `Field`. Feast 0.21 and onwards will not "
                    "support the `features` parameter."
                ),
                DeprecationWarning,
            )

        _sources = sources or inputs
        if inputs and sources:
            raise ValueError("At most one of `sources` or `inputs` can be specified.")
        elif inputs:
            warnings.warn(
                (
                    "The `inputs` parameter is being deprecated. Please use `sources` instead. "
                    "Feast 0.21 and onwards will not support the `inputs` parameter."
                ),
                DeprecationWarning,
            )

        _udf = udf

        if args:
            warnings.warn(
                (
                    "On demand feature view parameters should be specified as keyword arguments "
                    "instead of positional arguments. Feast 0.23 and onwards will not support "
                    "positional arguments in on demand feature view definitions."
                ),
                DeprecationWarning,
            )
            if len(args) > len(positional_attributes):
                raise ValueError(
                    f"Only {', '.join(positional_attributes)} are allowed as positional args "
                    f"when defining feature views, for backwards compatibility."
                )
            if len(args) >= 1:
                _name = args[0]
            if len(args) >= 2:
                _schema = args[1]
                # Convert Features to Fields.
                if len(_schema) > 0 and isinstance(_schema[0], Feature):
                    _schema = [Field.from_feature(feature) for feature in _schema]
                warnings.warn(
                    (
                        "The `features` parameter is being deprecated in favor of the `schema` parameter. "
                        "Please switch from using `features` to `schema`. This will also requiring switching "
                        "feature definitions from using `Feature` to `Field`. Feast 0.21 and onwards will not "
                        "support the `features` parameter."
                    ),
                    DeprecationWarning,
                )
            if len(args) >= 3:
                _sources = args[2]
                warnings.warn(
                    (
                        "The `inputs` parameter is being deprecated. Please use `sources` instead. "
                        "Feast 0.21 and onwards will not support the `inputs` parameter."
                    ),
                    DeprecationWarning,
                )
            if len(args) >= 4:
                _udf = args[3]

        if not _name:
            raise ValueError(
                "The name of the on demand feature view must be specified."
            )

        if not _sources:
            raise ValueError("The `sources` parameter must be specified.")

        super().__init__(
            name=_name,
            features=_schema,
            description=description,
            tags=tags,
            owner=owner,
        )

        assert _sources is not None
        self.source_feature_view_projections: Dict[str, FeatureViewProjection] = {}
        self.source_request_sources: Dict[str, RequestSource] = {}
        for source_name, odfv_source in _sources.items():
            if isinstance(odfv_source, RequestSource):
                self.source_request_sources[source_name] = odfv_source
            elif isinstance(odfv_source, FeatureViewProjection):
                self.source_feature_view_projections[source_name] = odfv_source
            else:
                self.source_feature_view_projections[
                    source_name
                ] = odfv_source.projection

        if _udf is None:
            raise ValueError("The `udf` parameter must be specified.")
        assert _udf
        self.udf = _udf

    @property
    def proto_class(self) -> Type[OnDemandFeatureViewProto]:
        return OnDemandFeatureViewProto

    def __copy__(self):
        fv = OnDemandFeatureView(
            name=self.name,
            schema=self.features,
            sources=dict(
                **self.source_feature_view_projections, **self.source_request_sources,
            ),
            udf=self.udf,
            description=self.description,
            tags=self.tags,
            owner=self.owner,
        )
        fv.projection = copy.copy(self.projection)
        return fv

    def __eq__(self, other):
        if not super().__eq__(other):
            return False

        if (
            not self.source_feature_view_projections
            == other.source_feature_view_projections
            or not self.source_request_sources == other.source_request_sources
            or not self.udf.__code__.co_code == other.udf.__code__.co_code
        ):
            return False

        return True

    def __hash__(self):
        return super().__hash__()

    def to_proto(self) -> OnDemandFeatureViewProto:
        """
        Converts an on demand feature view object to its protobuf representation.

        Returns:
            A OnDemandFeatureViewProto protobuf.
        """
        meta = OnDemandFeatureViewMeta()
        if self.created_timestamp:
            meta.created_timestamp.FromDatetime(self.created_timestamp)
        if self.last_updated_timestamp:
            meta.last_updated_timestamp.FromDatetime(self.last_updated_timestamp)
        sources = {}
        for source_name, fv_projection in self.source_feature_view_projections.items():
            sources[source_name] = OnDemandSource(
                feature_view_projection=fv_projection.to_proto()
            )
        for (source_name, request_sources,) in self.source_request_sources.items():
            sources[source_name] = OnDemandSource(
                request_data_source=request_sources.to_proto()
            )

        spec = OnDemandFeatureViewSpec(
            name=self.name,
            features=[feature.to_proto() for feature in self.features],
            sources=sources,
            user_defined_function=UserDefinedFunctionProto(
                name=self.udf.__name__, body=dill.dumps(self.udf, recurse=True),
            ),
            description=self.description,
            tags=self.tags,
            owner=self.owner,
        )

        return OnDemandFeatureViewProto(spec=spec, meta=meta)

    @classmethod
    def from_proto(cls, on_demand_feature_view_proto: OnDemandFeatureViewProto):
        """
        Creates an on demand feature view from a protobuf representation.

        Args:
            on_demand_feature_view_proto: A protobuf representation of an on-demand feature view.

        Returns:
            A OnDemandFeatureView object based on the on-demand feature view protobuf.
        """
        sources = {}
        for (
            source_name,
            on_demand_source,
        ) in on_demand_feature_view_proto.spec.sources.items():
            if on_demand_source.WhichOneof("source") == "feature_view":
                sources[source_name] = FeatureView.from_proto(
                    on_demand_source.feature_view
                ).projection
            elif on_demand_source.WhichOneof("source") == "feature_view_projection":
                sources[source_name] = FeatureViewProjection.from_proto(
                    on_demand_source.feature_view_projection
                )
            else:
                sources[source_name] = RequestSource.from_proto(
                    on_demand_source.request_data_source
                )
        on_demand_feature_view_obj = cls(
            name=on_demand_feature_view_proto.spec.name,
            schema=[
                Field(
                    name=feature.name,
                    dtype=from_value_type(ValueType(feature.value_type)),
                )
                for feature in on_demand_feature_view_proto.spec.features
            ],
            sources=sources,
            udf=dill.loads(
                on_demand_feature_view_proto.spec.user_defined_function.body
            ),
            description=on_demand_feature_view_proto.spec.description,
            tags=dict(on_demand_feature_view_proto.spec.tags),
            owner=on_demand_feature_view_proto.spec.owner,
        )

        # FeatureViewProjections are not saved in the OnDemandFeatureView proto.
        # Create the default projection.
        on_demand_feature_view_obj.projection = FeatureViewProjection.from_definition(
            on_demand_feature_view_obj
        )

        if on_demand_feature_view_proto.meta.HasField("created_timestamp"):
            on_demand_feature_view_obj.created_timestamp = (
                on_demand_feature_view_proto.meta.created_timestamp.ToDatetime()
            )
        if on_demand_feature_view_proto.meta.HasField("last_updated_timestamp"):
            on_demand_feature_view_obj.last_updated_timestamp = (
                on_demand_feature_view_proto.meta.last_updated_timestamp.ToDatetime()
            )

        return on_demand_feature_view_obj

    def get_request_data_schema(self) -> Dict[str, ValueType]:
        schema: Dict[str, ValueType] = {}
        for request_source in self.source_request_sources.values():
            if isinstance(request_source.schema, List):
                new_schema = {}
                for field in request_source.schema:
                    new_schema[field.name] = field.dtype.to_value_type()
                schema.update(new_schema)
            elif isinstance(request_source.schema, Dict):
                schema.update(request_source.schema)
            else:
                raise Exception(
                    f"Request source schema is not correct type: ${str(type(request_source.schema))}"
                )
        return schema

    def get_transformed_features_df(
        self, df_with_features: pd.DataFrame, full_feature_names: bool = False,
    ) -> pd.DataFrame:
        # Apply on demand transformations
        columns_to_cleanup = []
        for source_fv_projection in self.source_feature_view_projections.values():
            for feature in source_fv_projection.features:
                full_feature_ref = f"{source_fv_projection.name}__{feature.name}"
                if full_feature_ref in df_with_features.keys():
                    # Make sure the partial feature name is always present
                    df_with_features[feature.name] = df_with_features[full_feature_ref]
                    columns_to_cleanup.append(feature.name)
                elif feature.name in df_with_features.keys():
                    # Make sure the full feature name is always present
                    df_with_features[full_feature_ref] = df_with_features[feature.name]
                    columns_to_cleanup.append(full_feature_ref)

        # Compute transformed values and apply to each result row
        df_with_transformed_features = self.udf.__call__(df_with_features)

        # Work out whether the correct columns names are used.
        rename_columns: Dict[str, str] = {}
        for feature in self.features:
            short_name = feature.name
            long_name = f"{self.projection.name_to_use()}__{feature.name}"
            if (
                short_name in df_with_transformed_features.columns
                and full_feature_names
            ):
                rename_columns[short_name] = long_name
            elif not full_feature_names:
                # Long name must be in dataframe.
                rename_columns[long_name] = short_name

        # Cleanup extra columns used for transformation
        df_with_features.drop(columns=columns_to_cleanup, inplace=True)
        return df_with_transformed_features.rename(columns=rename_columns)

    def infer_features(self):
        """
        Infers the set of features associated to this feature view from the input source.

        Raises:
            RegistryInferenceFailure: The set of features could not be inferred.
        """
        df = pd.DataFrame()
        for feature_view_projection in self.source_feature_view_projections.values():
            for feature in feature_view_projection.features:
                dtype = feast_value_type_to_pandas_type(feature.dtype.to_value_type())
                df[f"{feature_view_projection.name}__{feature.name}"] = pd.Series(
                    dtype=dtype
                )
                df[f"{feature.name}"] = pd.Series(dtype=dtype)
        for request_data in self.source_request_sources.values():
            for field in request_data.schema:
                dtype = feast_value_type_to_pandas_type(field.dtype.to_value_type())
                df[f"{field.name}"] = pd.Series(dtype=dtype)
        output_df: pd.DataFrame = self.udf.__call__(df)
        inferred_features = []
        for f, dt in zip(output_df.columns, output_df.dtypes):
            inferred_features.append(
                Field(
                    name=f,
                    dtype=from_value_type(
                        python_type_to_feast_value_type(f, type_name=str(dt))
                    ),
                )
            )

        if self.features:
            missing_features = []
            for specified_features in self.features:
                if specified_features not in inferred_features:
                    missing_features.append(specified_features)
            if missing_features:
                raise SpecifiedFeaturesNotPresentError(
                    [f.name for f in missing_features], self.name
                )
        else:
            self.features = inferred_features

        if not self.features:
            raise RegistryInferenceFailure(
                "OnDemandFeatureView",
                f"Could not infer Features for the feature view '{self.name}'.",
            )

    @staticmethod
    def get_requested_odfvs(feature_refs, project, registry):
        all_on_demand_feature_views = registry.list_on_demand_feature_views(
            project, allow_cache=True
        )
        requested_on_demand_feature_views: List[OnDemandFeatureView] = []
        for odfv in all_on_demand_feature_views:
            for feature in odfv.features:
                if f"{odfv.name}:{feature.name}" in feature_refs:
                    requested_on_demand_feature_views.append(odfv)
                    break
        return requested_on_demand_feature_views


# TODO(felixwang9817): Force this decorator to accept kwargs and switch from
# `features` to `schema`.
def on_demand_feature_view(
    *args,
    features: Optional[List[Feature]] = None,
    sources: Optional[Dict[str, Union[FeatureView, RequestSource]]] = None,
    inputs: Optional[Dict[str, Union[FeatureView, RequestSource]]] = None,
    schema: Optional[List[Field]] = None,
    description: str = "",
    tags: Optional[Dict[str, str]] = None,
    owner: str = "",
):
    """
    Creates an OnDemandFeatureView object with the given user function as udf.

    Args:
        features (deprecated): The list of features in the output of the on demand
            feature view, after the transformation has been applied.
        sources (optional): A map from input source names to the actual input sources,
            which may be feature views, feature view projections, or request data sources.
            These sources serve as inputs to the udf, which will refer to them by name.
        inputs (optional): A map from input source names to the actual input sources,
            which may be feature views, feature view projections, or request data sources.
            These sources serve as inputs to the udf, which will refer to them by name.
        schema (optional): The list of features in the output of the on demand feature
            view, after the transformation has been applied.
        description (optional): A human-readable description.
        tags (optional): A dictionary of key-value pairs to store arbitrary metadata.
        owner (optional): The owner of the on demand feature view, typically the email
            of the primary maintainer.
    """
    positional_attributes = ["features", "inputs"]

    _schema = schema or []
    if len(_schema) == 0 and features is not None:
        _schema = [Field.from_feature(feature) for feature in features]
    if features is not None:
        warnings.warn(
            (
                "The `features` parameter is being deprecated in favor of the `schema` parameter. "
                "Please switch from using `features` to `schema`. This will also requiring switching "
                "feature definitions from using `Feature` to `Field`. Feast 0.21 and onwards will not "
                "support the `features` parameter."
            ),
            DeprecationWarning,
        )

    _sources = sources or inputs
    if inputs and sources:
        raise ValueError("At most one of `sources` or `inputs` can be specified.")
    elif inputs:
        warnings.warn(
            (
                "The `inputs` parameter is being deprecated. Please use `sources` instead. "
                "Feast 0.21 and onwards will not support the `inputs` parameter."
            ),
            DeprecationWarning,
        )

    if args:
        warnings.warn(
            (
                "On demand feature view parameters should be specified as keyword arguments "
                "instead of positional arguments. Feast 0.23 and onwards will not support "
                "positional arguments in on demand feature view definitions."
            ),
            DeprecationWarning,
        )
        if len(args) > len(positional_attributes):
            raise ValueError(
                f"Only {', '.join(positional_attributes)} are allowed as positional args "
                f"when defining feature views, for backwards compatibility."
            )
        if len(args) >= 1:
            _schema = args[0]
            # Convert Features to Fields.
            if len(_schema) > 0 and isinstance(_schema[0], Feature):
                _schema = [Field.from_feature(feature) for feature in _schema]
            warnings.warn(
                (
                    "The `features` parameter is being deprecated in favor of the `schema` parameter. "
                    "Please switch from using `features` to `schema`. This will also requiring switching "
                    "feature definitions from using `Feature` to `Field`. Feast 0.21 and onwards will not "
                    "support the `features` parameter."
                ),
                DeprecationWarning,
            )
        if len(args) >= 2:
            _sources = args[1]
            warnings.warn(
                (
                    "The `inputs` parameter is being deprecated. Please use `sources` instead. "
                    "Feast 0.21 and onwards will not support the `inputs` parameter."
                ),
                DeprecationWarning,
            )

    if not _sources:
        raise ValueError("The `sources` parameter must be specified.")

    def decorator(user_function):
        on_demand_feature_view_obj = OnDemandFeatureView(
            name=user_function.__name__,
            sources=_sources,
            schema=_schema,
            udf=user_function,
            description=description,
            tags=tags,
            owner=owner,
        )
        functools.update_wrapper(
            wrapper=on_demand_feature_view_obj, wrapped=user_function
        )
        return on_demand_feature_view_obj

    return decorator
