from __future__ import annotations

import copy
import inspect
import pickle
from pathlib import Path
from typing import Optional, Sequence

import numpy as np

from adaptive_rl_feature_subspace_boosting import (
    AdaptiveRLFeatureSubspaceBoostingClassifier,
)
from class_aware_heterogeneous_stacking import (
    ClassAwareHeterogeneousStackingClassifier,
    build_standard_base_estimators,
)


class BelowOneRLGradeRegressor:
    """Two-stage low-grade classifier + regular-grade regressor.

    Stage 1
    -------
    Predict whether the grade is below ``boundary`` using a heterogeneous,
    class-aware stacking classifier composed of:

      * ARL-FSGB
      * full-feature RL gradient boosting classifier
      * balanced Random Forest
      * balanced Extra Trees
      * Histogram Gradient Boosting
      * LightGBM when installed

    Stage 2
    -------
    For samples predicted as regular class, predict the grade using the
    supplied RL regressor.

    For samples predicted as the low class, the returned grade is controlled by
    ``low_grade_output``:

      * "classifier_probability":
          boundary * (1 - P(low)); produces a continuous value in [0,boundary]
      * "zero":
          always predicts 0 for low-class samples
      * "training_mean":
          predicts the mean low-grade target observed during training
      * numeric value:
          predicts that fixed value, clipped to [0,boundary]

    Important
    ---------
    X_val/y_val must be taken from the training fold. Do not use the test fold
    for adaptive feature selection, stacking, or threshold optimization.
    """

    def __init__(
        self,
        boundary: float = 1.0,
        low_grade_threshold: Optional[float] = None,
        low_class_weight: float = 5.0,
        low_grade_output="classifier_probability",

        classifier_feature_names: Optional[Sequence[str]] = None,

        # ------------------------------------------------------------------
        # ARL-FSGB configuration
        # ------------------------------------------------------------------
        classifier_n_rounds: int = 30,
        classifier_subspace_sizes=(0.25, 0.40, 0.55),
        classifier_correlation_threshold: float = 0.85,
        classifier_maximum_features_per_cluster: int = 3,
        classifier_exploration_rate: float = 0.20,
        classifier_exploration_decay: float = 0.97,
        classifier_feature_learning_rate: float = 0.35,
        classifier_max_selected_models: int = 5,

        classifier_entropy_bins: int = 16,
        classifier_maximum_missing_fraction: float = 0.90,
        classifier_minimum_unique_values: int = 2,

        # ------------------------------------------------------------------
        # Stacking configuration
        # ------------------------------------------------------------------
        stacking_blender_fraction: float = 0.50,
        stacking_include_lightgbm: bool = True,
        stacking_include_hist_gradient_boosting: bool = True,
        stacking_include_full_rl_classifier: bool = True,

        stacking_minimum_majority_recall: float = 0.985,
        stacking_minimum_minority_recall: float = 0.20,

        stacking_reward_minority_f1_weight: float = 0.35,
        stacking_reward_minority_recall_weight: float = 0.30,
        stacking_reward_majority_recall_weight: float = 0.20,
        stacking_reward_balanced_accuracy_weight: float = 0.15,

        # ------------------------------------------------------------------
        # Custom RL classifier settings
        # ------------------------------------------------------------------
        classifier_learning_rate: float = 0.05,
        classifier_n_estimators: int = 100,
        classifier_min_samples: int = 10,
        classifier_max_depth: int = 3,
        classifier_min_gain: float = 1e-6,
        classifier_max_thresholds: int = 64,
        classifier_class_weight="sqrt_balanced",
        classifier_minority_weight_fraction: float = 0.25,
        classifier_prior_strength: float = 0.50,
        classifier_early_stopping_rounds: int = 8,
        classifier_minimum_improvement: float = 1e-4,

        # ------------------------------------------------------------------
        # RL regular-grade regressor settings
        # ------------------------------------------------------------------
        rl_learning_rate: float = 0.10,
        rl_n_estimators: int = 20,
        rl_min_samples: int = 10,
        rl_max_depth: int = 4,
        rl_actions=(0.25, 0.50, 1.00, 1.50, 2.00),

        regression_lower_bound: Optional[float] = None,
        regression_upper_bound: float = 4.0,

        # Dependency injection. These are classes or callables.
        rl_classifier_class=None,
        rl_regressor_class=None,

        random_state: int = 42,
        verbose: bool = True,
    ):
        self.boundary = float(boundary)
        self.low_grade_threshold = (
            None
            if low_grade_threshold is None
            else float(low_grade_threshold)
        )
        self.low_class_weight = float(low_class_weight)
        self.low_grade_output = low_grade_output

        self.classifier_feature_names = (
            None
            if classifier_feature_names is None
            else list(classifier_feature_names)
        )

        self.classifier_n_rounds = int(classifier_n_rounds)
        self.classifier_subspace_sizes = tuple(
            classifier_subspace_sizes
        )
        self.classifier_correlation_threshold = float(
            classifier_correlation_threshold
        )
        self.classifier_maximum_features_per_cluster = int(
            classifier_maximum_features_per_cluster
        )
        self.classifier_exploration_rate = float(
            classifier_exploration_rate
        )
        self.classifier_exploration_decay = float(
            classifier_exploration_decay
        )
        self.classifier_feature_learning_rate = float(
            classifier_feature_learning_rate
        )
        self.classifier_max_selected_models = int(
            classifier_max_selected_models
        )

        self.classifier_entropy_bins = int(classifier_entropy_bins)
        self.classifier_maximum_missing_fraction = float(
            classifier_maximum_missing_fraction
        )
        self.classifier_minimum_unique_values = int(
            classifier_minimum_unique_values
        )

        self.stacking_blender_fraction = float(
            stacking_blender_fraction
        )
        self.stacking_include_lightgbm = bool(
            stacking_include_lightgbm
        )
        self.stacking_include_hist_gradient_boosting = bool(
            stacking_include_hist_gradient_boosting
        )
        self.stacking_include_full_rl_classifier = bool(
            stacking_include_full_rl_classifier
        )

        self.stacking_minimum_majority_recall = float(
            stacking_minimum_majority_recall
        )
        self.stacking_minimum_minority_recall = float(
            stacking_minimum_minority_recall
        )

        self.stacking_reward_minority_f1_weight = float(
            stacking_reward_minority_f1_weight
        )
        self.stacking_reward_minority_recall_weight = float(
            stacking_reward_minority_recall_weight
        )
        self.stacking_reward_majority_recall_weight = float(
            stacking_reward_majority_recall_weight
        )
        self.stacking_reward_balanced_accuracy_weight = float(
            stacking_reward_balanced_accuracy_weight
        )

        self.classifier_learning_rate = float(
            classifier_learning_rate
        )
        self.classifier_n_estimators = int(
            classifier_n_estimators
        )
        self.classifier_min_samples = int(classifier_min_samples)
        self.classifier_max_depth = int(classifier_max_depth)
        self.classifier_min_gain = float(classifier_min_gain)
        self.classifier_max_thresholds = int(
            classifier_max_thresholds
        )
        self.classifier_class_weight = classifier_class_weight
        self.classifier_minority_weight_fraction = float(
            classifier_minority_weight_fraction
        )
        self.classifier_prior_strength = float(
            classifier_prior_strength
        )
        self.classifier_early_stopping_rounds = int(
            classifier_early_stopping_rounds
        )
        self.classifier_minimum_improvement = float(
            classifier_minimum_improvement
        )

        self.rl_learning_rate = float(rl_learning_rate)
        self.rl_n_estimators = int(rl_n_estimators)
        self.rl_min_samples = int(rl_min_samples)
        self.rl_max_depth = int(rl_max_depth)
        self.rl_actions = list(rl_actions)

        self.regression_lower_bound = (
            self.boundary
            if regression_lower_bound is None
            else float(regression_lower_bound)
        )
        self.regression_upper_bound = float(
            regression_upper_bound
        )

        self.rl_classifier_class = rl_classifier_class
        self.rl_regressor_class = rl_regressor_class

        self.random_state = int(random_state)
        self.verbose = bool(verbose)

        self._validate_parameters()
        self._reset_fitted_state()

    def _validate_parameters(self):
        if self.boundary < 0:
            raise ValueError("boundary must be non-negative.")

        if (
            self.regression_upper_bound
            < self.regression_lower_bound
        ):
            raise ValueError(
                "regression_upper_bound must be >= "
                "regression_lower_bound."
            )

        reward_sum = (
            self.stacking_reward_minority_f1_weight
            + self.stacking_reward_minority_recall_weight
            + self.stacking_reward_majority_recall_weight
            + self.stacking_reward_balanced_accuracy_weight
        )
        if not np.isclose(reward_sum, 1.0):
            raise ValueError(
                "The four stacking reward weights must sum to 1."
            )

        if self.rl_classifier_class is None:
            raise ValueError(
                "Pass rl_classifier_class="
                "RL_GradientBoostingClassifierfromScratch."
            )

        if self.rl_regressor_class is None:
            raise ValueError(
                "Pass rl_regressor_class="
                "RL_GradientBoostingRegressorScratch "
                "(or your current RL regressor class)."
            )

    def _reset_fitted_state(self):
        self.low_grade_classifier = None
        self.regular_grade_regressor = None

        self.n_features_in_ = None
        self.low_grade_training_mean_ = 0.0
        self.classification_threshold_ = 0.5

        self.n_low_train_ = 0
        self.n_regular_train_ = 0

        self.is_fitted_ = False

    @staticmethod
    def _prepare_X(X):
        if hasattr(X, "to_numpy"):
            X = X.to_numpy()

        X = np.asarray(X, dtype=np.float64)

        if X.ndim != 2:
            raise ValueError(
                f"X must be 2-dimensional; received {X.shape}."
            )

        return np.nan_to_num(
            X,
            nan=0.0,
            posinf=0.0,
            neginf=0.0,
        )

    @staticmethod
    def _prepare_y(y):
        if hasattr(y, "to_numpy"):
            y = y.to_numpy()

        y = np.asarray(y, dtype=np.float64).reshape(-1)

        if y.size == 0:
            raise ValueError("y cannot be empty.")

        if not np.isfinite(y).all():
            raise ValueError("y contains NaN or infinite values.")

        return y

    @staticmethod
    def _construct_with_supported_arguments(
        estimator_class,
        candidate_arguments,
    ):
        """Construct a custom estimator without assuming every parameter exists."""

        signature = inspect.signature(estimator_class.__init__)
        supported = signature.parameters

        filtered = {
            key: value
            for key, value in candidate_arguments.items()
            if key in supported
        }

        return estimator_class(**filtered)

    @staticmethod
    def _fit_with_optional_validation(
        estimator,
        X,
        y,
        X_val=None,
        y_val=None,
    ):
        signature = inspect.signature(estimator.fit)
        parameters = signature.parameters

        keyword_arguments = {}

        if (
            X_val is not None
            and y_val is not None
            and "X_val" in parameters
            and "y_val" in parameters
        ):
            keyword_arguments["X_val"] = X_val
            keyword_arguments["y_val"] = y_val

        estimator.fit(X, y, **keyword_arguments)
        return estimator

    def _build_rl_classifier(
        self,
        seed,
        verbose=False,
    ):
        candidate_arguments = {
            "learning_rate": self.classifier_learning_rate,
            "n_estimators": self.classifier_n_estimators,
            "min_samples": self.classifier_min_samples,
            "max_depth": self.classifier_max_depth,
            "min_gain": self.classifier_min_gain,
            "max_thresholds": self.classifier_max_thresholds,

            "class_weight": self.classifier_class_weight,
            "minority_weight_fraction": (
                self.classifier_minority_weight_fraction
            ),
            "positive_class": 1,
            "prior_strength": self.classifier_prior_strength,

            "decision_threshold": "auto",
            "threshold_metric": "constrained_f1",
            "minimum_majority_recall": (
                self.stacking_minimum_majority_recall
            ),
            "minimum_minority_recall": (
                self.stacking_minimum_minority_recall
            ),

            "early_stopping_rounds": (
                self.classifier_early_stopping_rounds
            ),
            "minimum_improvement": (
                self.classifier_minimum_improvement
            ),

            "random_state": seed,
            "verbose": verbose,
        }

        return self._construct_with_supported_arguments(
            self.rl_classifier_class,
            candidate_arguments,
        )

    def _build_arl_fsgb_classifier(self):
        base_classifier = self._build_rl_classifier(
            seed=self.random_state,
            verbose=False,
        )

        return AdaptiveRLFeatureSubspaceBoostingClassifier(
            base_estimator=base_classifier,
            feature_names=self.classifier_feature_names,
            positive_class=1,

            entropy_bins=self.classifier_entropy_bins,
            maximum_missing_fraction=(
                self.classifier_maximum_missing_fraction
            ),
            minimum_unique_values=(
                self.classifier_minimum_unique_values
            ),

            initial_information_gain_weight=0.75,
            initial_entropy_weight=0.15,
            initial_coverage_weight=0.10,

            correlation_threshold=(
                self.classifier_correlation_threshold
            ),
            correlation_sample_size=12000,

            n_rounds=self.classifier_n_rounds,
            subspace_sizes=self.classifier_subspace_sizes,
            minimum_features_per_subspace=12,
            maximum_features_per_cluster=(
                self.classifier_maximum_features_per_cluster
            ),

            exploration_rate=self.classifier_exploration_rate,
            exploration_decay=self.classifier_exploration_decay,
            minimum_exploration_rate=0.05,
            feature_learning_rate=(
                self.classifier_feature_learning_rate
            ),
            feature_probability_floor=1e-5,
            probability_temperature=0.80,

            reward_minority_f1_weight=(
                self.stacking_reward_minority_f1_weight
            ),
            reward_minority_recall_weight=(
                self.stacking_reward_minority_recall_weight
            ),
            reward_majority_recall_weight=(
                self.stacking_reward_majority_recall_weight
            ),
            reward_balanced_accuracy_weight=(
                self.stacking_reward_balanced_accuracy_weight
            ),

            minimum_majority_recall=(
                self.stacking_minimum_majority_recall
            ),
            minimum_minority_recall=(
                self.stacking_minimum_minority_recall
            ),
            majority_recall_penalty=1.50,
            minority_recall_penalty=0.75,

            max_selected_models=(
                self.classifier_max_selected_models
            ),
            diversity_strength=0.25,

            decision_threshold="auto",
            threshold_min=0.05,
            threshold_max=0.95,
            threshold_grid_size=181,

            random_state=self.random_state,
            verbose=self.verbose,
        )

    def _build_stacking_classifier(self):
        arl_fsgb = self._build_arl_fsgb_classifier()

        full_rl_classifier = None

        if self.stacking_include_full_rl_classifier:
            full_rl_classifier = self._build_rl_classifier(
                seed=self.random_state + 1,
                verbose=False,
            )

        estimators = build_standard_base_estimators(
            arl_fsgb_estimator=arl_fsgb,
            rl_classifier_estimator=full_rl_classifier,
            random_state=self.random_state,
            include_lightgbm=self.stacking_include_lightgbm,
        )

        if not self.stacking_include_hist_gradient_boosting:
            estimators.pop("hist_gradient_boosting", None)

        return ClassAwareHeterogeneousStackingClassifier(
            estimators=estimators,

            positive_class=1,

            blender_fraction=(
                self.stacking_blender_fraction
            ),

            reward_minority_f1_weight=(
                self.stacking_reward_minority_f1_weight
            ),

            reward_minority_recall_weight=(
                self.stacking_reward_minority_recall_weight
            ),

            reward_majority_recall_weight=(
                self.stacking_reward_majority_recall_weight
            ),

            reward_balanced_accuracy_weight=(
                self.stacking_reward_balanced_accuracy_weight
            ),

            minimum_majority_recall=(
                self.stacking_minimum_majority_recall
            ),

            minimum_minority_recall=(
                self.stacking_minimum_minority_recall
            ),

            majority_recall_penalty=1.50,
            minority_recall_penalty=0.75,

            threshold_min=0.05,
            threshold_max=0.95,
            threshold_grid_size=181,

            random_state=self.random_state,
            verbose=self.verbose,
        )

    def _build_regular_grade_regressor(self):
        candidate_arguments = {
            "learning_rate": self.rl_learning_rate,
            "n_estimators": self.rl_n_estimators,
            "min_samples": self.rl_min_samples,
            "max_depth": self.rl_max_depth,
            "actions": self.rl_actions,

            "random_state": self.random_state,
            "verbose": self.verbose,
        }

        return self._construct_with_supported_arguments(
            self.rl_regressor_class,
            candidate_arguments,
        )

    def fit(
        self,
        X,
        y,
        X_val=None,
        y_val=None,
    ):
        if X_val is None or y_val is None:
            raise ValueError(
                "X_val and y_val are required. They must be split "
                "from the training fold, not taken from the test fold."
            )

        X = self._prepare_X(X)
        y = self._prepare_y(y)
        X_val = self._prepare_X(X_val)
        y_val = self._prepare_y(y_val)

        if X.shape[0] != y.shape[0]:
            raise ValueError("X and y have different sample counts.")

        if X_val.shape[0] != y_val.shape[0]:
            raise ValueError(
                "X_val and y_val have different sample counts."
            )

        if X.shape[1] != X_val.shape[1]:
            raise ValueError(
                "X and X_val have different feature counts."
            )

        self._reset_fitted_state()
        self.n_features_in_ = X.shape[1]

        if (
            self.classifier_feature_names is not None
            and len(self.classifier_feature_names)
            != self.n_features_in_
        ):
            raise ValueError(
                "classifier_feature_names does not match "
                "the number of columns in X."
            )

        y_is_low = (y < self.boundary).astype(np.int64)
        y_val_is_low = (
            y_val < self.boundary
        ).astype(np.int64)

        self.n_low_train_ = int(np.sum(y_is_low == 1))
        self.n_regular_train_ = int(np.sum(y_is_low == 0))

        if self.n_low_train_ == 0:
            raise ValueError(
                "The training data contains no grades below boundary."
            )

        if self.n_regular_train_ == 0:
            raise ValueError(
                "The training data contains no grades at/above boundary."
            )

        self.low_grade_training_mean_ = float(
            np.mean(y[y_is_low == 1])
        )

        if self.verbose:
            print(
                f"X.shape, y_is_low.shape: {X.shape} "
                f"{y_is_low.shape}"
            )
            print(
                f"X_val.shape, y_val_is_low.shape: "
                f"{X_val.shape} {y_val_is_low.shape}"
            )
            print(f"Positive samples: {self.n_low_train_}")
            print(f"Negative samples: {self.n_regular_train_}")
            print(
                "Raw scale_pos_weight: "
                f"{self.n_regular_train_ / self.n_low_train_:.6f}"
            )

        # --------------------------------------------------------------
        # Stage 1: heterogeneous low-grade classifier
        # --------------------------------------------------------------
        self.low_grade_classifier = (
            self._build_stacking_classifier()
        )

        self.low_grade_classifier.fit(
            X,
            y_is_low,
            X_val=X_val,
            y_val=y_val_is_low,
        )

        self.classification_threshold_ = float(
            self.low_grade_classifier.classification_threshold_
        )

        # An explicit call-site threshold overrides the learned threshold.
        if self.low_grade_threshold is not None:
            self.classification_threshold_ = (
                self.low_grade_threshold
            )

        # --------------------------------------------------------------
        # Stage 2: regular-grade regressor
        # --------------------------------------------------------------
        regular_train_mask = y_is_low == 0
        regular_val_mask = y_val_is_low == 0

        X_regular = X[regular_train_mask]
        y_regular = y[regular_train_mask]

        X_val_regular = X_val[regular_val_mask]
        y_val_regular = y_val[regular_val_mask]

        if self.verbose:
            print(
                "X_val_regular.shape, y_val_regular.shape: "
                f"{X_val_regular.shape} {y_val_regular.shape}"
            )

        self.regular_grade_regressor = (
            self._build_regular_grade_regressor()
        )

        self._fit_with_optional_validation(
            self.regular_grade_regressor,
            X_regular,
            y_regular,
            X_val=X_val_regular,
            y_val=y_val_regular,
        )

        self.is_fitted_ = True

        if self.verbose:
            print("\nBelow-one heterogeneous grade model fitted")
            print(
                f"Classification boundary: {self.boundary:.2f}"
            )
            print(
                f"Samples below boundary: {self.n_low_train_}"
            )
            print(
                f"Samples at/above boundary: "
                f"{self.n_regular_train_}"
            )
            print(
                f"Final low-grade threshold: "
                f"{self.classification_threshold_:.4f}"
            )
            print(
                f"Low-grade class weight: "
                f"{self.low_class_weight:.2f}"
            )
            print(
                "Regression range: "
                f"[{self.regression_lower_bound:.2f}, "
                f"{self.regression_upper_bound:.2f}]"
            )

        return self

    def _check_fitted(self):
        if not self.is_fitted_:
            raise RuntimeError(
                "BelowOneRLGradeRegressor must be fitted first."
            )

    def predict_low_probability(self, X):
        self._check_fitted()
        X = self._prepare_X(X)

        if X.shape[1] != self.n_features_in_:
            raise ValueError(
                f"Expected {self.n_features_in_} features; "
                f"received {X.shape[1]}."
            )

        return (
            self.low_grade_classifier
            .predict_positive_proba(X)
        )

    def predict_low_class(self, X, threshold=None):
        threshold = (
            self.classification_threshold_
            if threshold is None
            else float(threshold)
        )

        probability = self.predict_low_probability(X)

        return (probability >= threshold).astype(np.int64)

    def _predict_low_grade_value(self, low_probability):
        if isinstance(self.low_grade_output, str):
            strategy = self.low_grade_output.lower()

            if strategy == "classifier_probability":
                # A larger P(low) produces a grade closer to zero.
                value = self.boundary * (
                    1.0 - low_probability
                )

            elif strategy == "zero":
                value = np.zeros_like(
                    low_probability,
                    dtype=np.float64,
                )

            elif strategy == "training_mean":
                value = np.full_like(
                    low_probability,
                    self.low_grade_training_mean_,
                    dtype=np.float64,
                )

            else:
                raise ValueError(
                    "Unknown low_grade_output strategy: "
                    f"{self.low_grade_output!r}."
                )
        else:
            value = np.full_like(
                low_probability,
                float(self.low_grade_output),
                dtype=np.float64,
            )

        return np.clip(value, 0.0, self.boundary)

    def predict(self, X):
        self._check_fitted()
        X = self._prepare_X(X)

        low_probability = self.predict_low_probability(X)

        low_mask = (
            low_probability
            >= self.classification_threshold_
        )

        # Predict regular grade for every row first. This avoids estimator
        # errors on an empty subset and keeps output indexing simple.
        regular_prediction = np.asarray(
            self.regular_grade_regressor.predict(X),
            dtype=np.float64,
        ).reshape(-1)

        regular_prediction = np.clip(
            regular_prediction,
            self.regression_lower_bound,
            self.regression_upper_bound,
        )

        prediction = regular_prediction.copy()

        if np.any(low_mask):
            prediction[low_mask] = (
                self._predict_low_grade_value(
                    low_probability[low_mask]
                )
            )

        return prediction

    def predict_components(self, X):
        """Return diagnostics for each row."""

        self._check_fitted()
        X = self._prepare_X(X)

        low_probability = self.predict_low_probability(X)
        low_class = (
            low_probability
            >= self.classification_threshold_
        ).astype(np.int64)

        regular_prediction = np.asarray(
            self.regular_grade_regressor.predict(X),
            dtype=np.float64,
        ).reshape(-1)

        regular_prediction = np.clip(
            regular_prediction,
            self.regression_lower_bound,
            self.regression_upper_bound,
        )

        final_prediction = self.predict(X)

        return {
            "low_probability": low_probability,
            "low_class": low_class,
            "regular_grade_prediction": regular_prediction,
            "final_grade_prediction": final_prediction,
        }

    def evaluate_classifier(self, X, y):
        self._check_fitted()
        X = self._prepare_X(X)
        y = self._prepare_y(y)

        y_is_low = (y < self.boundary).astype(np.int64)

        return self.low_grade_classifier.evaluate_binary(
            X,
            y_is_low,
            threshold=self.classification_threshold_,
        )

    def get_base_classifier_report(self):
        self._check_fitted()
        return (
            self.low_grade_classifier
            .get_base_model_report()
        )

    def get_meta_classifier_coefficients(self):
        self._check_fitted()
        return (
            self.low_grade_classifier
            .get_meta_coefficients()
        )

    def get_arl_feature_report(self):
        """Return the ARL feature-policy report when ARL-FSGB was retained."""

        self._check_fitted()

        arl_model = (
            self.low_grade_classifier
            .fitted_estimators_
            .get("arl_fsgb")
        )

        if arl_model is None:
            return []

        method = getattr(
            arl_model,
            "get_feature_policy_report",
            None,
        )

        return [] if method is None else method()

    def save_model(self, path):
        path = Path(path)
        path.parent.mkdir(parents=True, exist_ok=True)

        with path.open("wb") as file:
            pickle.dump(self, file)

    @staticmethod
    def load_model(path):
        with Path(path).open("rb") as file:
            model = pickle.load(file)

        if not isinstance(model, BelowOneRLGradeRegressor):
            raise TypeError(
                "The loaded object is not "
                "BelowOneRLGradeRegressor."
            )

        return model
