import numpy as np
import pandas as pd
from .preprocessor import DataPreprocessor
from .feature_engineer import MixSADFeatureEngineer
from .prediction_builder import PredictionBuilder

class MixSADPipeline:
    """
    Orchestrates the end-to-end anomaly detection process using a
    direct supervised prediction approach for high performance.
    """
    def __init__(self, random_state=42):
        self.preprocessor = DataPreprocessor()
        self.feature_engineer = MixSADFeatureEngineer(random_state=random_state)
        self.prediction_builder = PredictionBuilder()

    def run(self, df_features, true_labels, threshold=0.5):
        """
        Executes the full supervised pipeline on a given DataFrame.

        Args:
            df_features (pd.DataFrame): The input data containing features.
            true_labels (pd.Series): The ground truth labels for evaluation and
                                     supervised feature generation.
            threshold (float): The probability threshold for classifying fraud.

        Returns:
            np.array: An array of final predictions (-1 for anomaly, 1 for normal).
        """
        X_num_scaled, X_cat = self.preprocessor.preprocess(df_features)
        
        # The feature engineer now requires true_labels to create the supervised 'fraud_score'.
        engineered_features = self.feature_engineer.engineer_features(
            X_num_scaled, X_cat, true_labels=true_labels
        )
        
        # The prediction builder uses the engineered features and threshold to make a final decision.
        print(f"\nApplying prediction threshold: {threshold}")
        final_predictions = self.prediction_builder.predict(engineered_features, threshold=threshold)

        # Evaluate the results.
        self.prediction_builder.evaluate(final_predictions, true_labels)

        return final_predictions
