
import numpy as np
import pandas as pd


#example with station M data
StationMcup = pd.read_csv("//atlas/ProjectLibrary/902305_Event_Detection_with_SES/Deployments/MARS2024B-2025/StationM_test.csv")


#atn is actually mass flux rescaled to atn scale
StationMcup['rm150'] = StationMcup['atn'].rolling(150, min_periods=24).mean()
StationMcup['slope'] = StationMcup['rm150'].diff()
#drop the first 150 samples
StationMcup = StationMcup.iloc[151:, ]


lowtrigger = 0.007
hightrigger = 0.011

#See if it passes the low trigger
StationMcup["rm150"] =  StationMcup['atn'].rolling(150, min_periods=23).mean()
StationMcup['slope'] = StationMcup['rm150'].diff()
StationMcup["trigger150slope"] = np.where(StationMcup['slope'] >= lowtrigger, 'LowTrigger', 'WaitSlope')

#find the rolling rate low triggers in past 953 samples (~1.5 months)
StationMcup['low_trigger_rate'] = (StationMcup['trigger150slope'] == 'LowTrigger').rolling(953, min_periods=2).sum()

#Line to help keep tabs on whether the switch has been flipped and we're now using the high trigger

StationMcup['max_rate'] = StationMcup['low_trigger_rate'].cummax()

try:
    # Ensure 'max_rate' column is not empty and the values are valid
    if 'max_rate' in StationMcup.columns and not StationMcup['max_rate'].isnull().all():
        # Apply condition element-wise to the 'max_rate' column
        StationMcup["Fire_trigger"] = np.where(
            StationMcup['max_rate'].abs() > 3,
            np.where(StationMcup['slope'] >= hightrigger, 'Fire', 'Wait'),
            np.where(StationMcup['slope'] >= lowtrigger, 'Fire', 'Wait')
        )
    else:
        print("The 'max_rate' column is missing or contains all NaN values.")
except Exception as e:
    print(f"An error occurred: {e}")

#if doesn't fire in ~21 days, fire anyway

matchlist = ['Wait'] * 444
matchlist.insert(0,'Fire')


def check_sequence(df, col_name, seq):
    """
    Checks if a sequence of values in a column matches a given list.

    Args:
        df: The DataFrame.
        col_name: The name of the column to check.
        seq: The sequence of strings to match.

    Returns:
        A new DataFrame with a 'match' column indicating if the sequence was found.
    """

    df['match'] = False
    for i in range(len(df) - len(seq) + 1):
        if df[col_name].iloc[i:i + len(seq)].tolist() == seq:
            df.loc[i + len(seq) - 1, 'match'] = True
    return df

# Example usage:
df = StationMcup
seq_to_match = matchlist

df = check_sequence(df, 'Fire_trigger', seq_to_match)


df['match'] = df['match'].astype(str)

df["Fire_anyway"] = np.where(df['match'].str.contains('T'), 'Fire', 'Wait')
