from .pipeline import run_pipeline

def timeseries_anomaly_detection(
    master_data, 
    group_columns, 
    variable,
    date_column, 
    freq="W-MON",
    min_records=None,  # Fixed: Capital 'N'
    contamination=0.03, 
    random_state=42,
    alpha=0.3, 
    sigma=1.5, 
    eval_period=1,
    prophet_CI=0.90, 
    mad_threshold=2, 
    mad_scale_factor=0.6745
):
    
    """
    Performs anomaly detection on grouped time-series data.

    This function identifies outliers within specific groups of data by analyzing 
    historical trends, applying statistical thresholds, and calculating 
    prediction intervals.

    Args:
        master_data (pd.DataFrame): The input dataset containing the time series.
        group_columns (list[str]): Columns used to partition the data (e.g., ['store_id', 'item_id']).
        variable (str): The target numerical column to analyze for anomalies.
        date_column (str): The column containing datetime information.
        freq (str): Frequency of the time series (Pandas offset alias). Defaults to 'W-MON'.
        max_records (int): Maximum historical records to consider for the model. Defaults to 104.
        min_records (int): Minimum records required to perform detection. Defaults to 15.
        contamination (float): Expected proportion of outliers in the data (0 to 0.5). Defaults to 0.03.
        random_state (int): Seed for reproducibility in stochastic models. Defaults to 42.
        alpha (float): Smoothing factor for trend calculations. Defaults to 0.3.
        sigma (float): Standard deviation multiplier for thresholding. Defaults to 1.5.
        eval_periods (int): Number of recent periods to evaluate for anomalies. Defaults to 1.
        interval_width (float): The confidence level for the prediction interval (0 to 1). Defaults to 0.9.

    Returns:
        tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame]:
            - final_results: The main dataframe containing original data, interpolated values, 
              forecasts, residuals, and anomaly flags (e.g., is_FB_anomaly, is_IQR_anomaly).
            - success_report: A summary table for successful groups showing 'initial_record_count', 
              'interpolated_record_count', and 'interpolation_pct'.
            - exclusion_report: A diagnostic table listing groups dropped from the analysis 
              and the specific reason (e.g., "Insufficient records" or "High Interpolation").
    """
    # --- 1. MANDATORY COLUMN VALIDATION ---
    mandatory_cols = group_columns + [variable, date_column]
    missing_cols = [col for col in mandatory_cols if col not in master_data.columns]
    
    if missing_cols:
        raise ValueError(
            f"CRITICAL ERROR: Mandatory columns missing from input DataFrame: {missing_cols}. "
            f"Please ensure group_columns, variable, and date_column are correctly spelled."
        )
        
    return run_pipeline(
        master_data=master_data,
        group_columns=group_columns,
        variable=variable,
        date_column=date_column,
        freq=freq,
        min_records=min_records,
        contamination=contamination,
        random_state=random_state,
        alpha=alpha,
        sigma=sigma,
        eval_period=eval_period,
        prophet_CI=prophet_CI,
        mad_threshold = mad_threshold, 
        mad_scale_factor = mad_scale_factor
        
    )
    
    print("Anomaly pipeline successfully invoked via python -m!")

# automate min_records based on eval_periods, 
# max_records = max_records + eval_records
# freq_daily: max_records based on frequency (for version 2) 104 for weekly

