from sklearn.base import BaseEstimator, TransformerMixin


class DFMergeTransformer(BaseEstimator, TransformerMixin):
    """
    Transformer for merging a DataFrame with another DataFrame within a scikit-learn pipeline.

    Parameters
    ----------
    df_to_merge : pd.DataFrame
        The DataFrame to merge into the input X.
    left_on : str
        Column name in X to join on.
    right_on : str
        Column name in df_to_merge to join on.
    how : str, default="left"
        Type of merge: 'left', 'right', 'inner', 'outer'.
    prefix : str, default=None
        Optional prefix to prepend to all columns from df_to_merge in the merged DataFrame.
    """

    def __init__(self, df_to_merge, left_on, right_on, how="left", prefix=None):
        self.df_to_merge = df_to_merge.copy()
        self.left_on = left_on
        self.right_on = right_on
        self.how = how
        self.prefix = prefix

    def fit(self, X, y=None):
        return self

    def transform(self, X):
        X = X.copy()
        df_to_merge = self.df_to_merge.copy()

        if self.prefix:
            df_to_merge = df_to_merge.add_prefix(self.prefix)

        right_on = self.right_on
        if self.prefix:
            right_on = self.prefix + self.right_on

        X_merged = X.merge(df_to_merge, how=self.how, left_on=self.left_on, right_on=right_on)

        return X_merged
