import pandas as pd
import numpy as np

from .Preprocessing import classify


# Anomaly category columns (optional, keep if you still want string labels)


def detect_outliers_percentile(group, variable,date_column,eval_period):
    n = len(group)
    if n < 10:
        # Optional: log specific keys if they exist in your scope
        return pd.DataFrame(columns=group.columns)

    group = group.copy()
    # Explicitly ensure date_column is datetime right at the start
    group[date_column] = pd.to_datetime(group[date_column])
    train_size = n - eval_period

    # --- 1. HANDLE TRAINING DATA (Initial Block) ---
    # Calculate baseline IQR using all data available before eval_period
    initial_train = group[variable].iloc[:train_size]
    
    low = initial_train.quantile(0.05)
    high= initial_train.quantile(0.95)
    
    # Assign initial bounds to the training rows
    group.loc[group.index[:train_size], 'set'] = "TRAIN"
    group.loc[group.index[:train_size], 'Percentile_low'] = low
    group.loc[group.index[:train_size], 'Percentile_high'] = high
    group.loc[group.index[:train_size], 'Percentile_anomaly'] = group[variable].iloc[:train_size].apply(
        lambda x: classify(x, low, high)
    )
    group.loc[group.index[:train_size], 'is_Percentile_anomaly'] = (
        (group[variable].iloc[:train_size] < low) | 
        (group[variable].iloc[:train_size] > high)
    )

    
    # --- 2. HANDLE EVALUATION DATA (Expanding Window) ---
    # Iterate through the eval period, increasing the training set one point at a time
    for i in range(train_size, n):
        # Data available up to this point (expanding)
        current_train = group[variable].iloc[:i]
        
        LOW = current_train.quantile(0.05)
        HIGH  = current_train.quantile(0.95)
    
        # Test the current point i
        current_val = group[variable].iloc[i]
        group.iloc[i, group.columns.get_loc('set')] = "TEST"
        group.iloc[i, group.columns.get_loc('Percentile_low')] = LOW
        group.iloc[i, group.columns.get_loc('Percentile_high')] = HIGH
        group.iloc[i, group.columns.get_loc('Percentile_anomaly')] = classify(current_val, LOW, HIGH)
        group.iloc[i, group.columns.get_loc('is_Percentile_anomaly')] = (current_val < LOW) or (current_val > HIGH)

    # Cast boolean column properly
    group['is_Percentile_anomaly'] = group['is_Percentile_anomaly'].astype(bool)
    # FINAL SAFETY CHECK
    group[date_column] = pd.to_datetime(group[date_column])
    
    return group

   