# -*- coding: utf-8 -*-
"""
Created on Tue Feb 24 20:44:11 2026

@author: chuffard
"""


import numpy as np
import pandas as pd
import sys
import os.path
import warnings

warnings.filterwarnings("ignore")

use_min_period = 24
filename = sys.argv[1]
nrec = int(sys.argv[2])

if (nrec < use_min_period):
    print("nrec minimum is", use_min_period)
    exit()
    
if (os.path.isfile(sys.argv[1]) == False):
    print("CSV file does not exist")
    exit()

# Load the data
sip_csv = pd.read_csv(sys.argv[1])

if (len(sip_csv) < nrec):
    print("Number or records is less than", nrec, "... keep on trucking")
    exit()

#atn is actually mass flux rescaled to atn scale
sip_csv['rm'] = sip_csv['atn'].rolling(nrec, min_periods=use_min_period).mean()
sip_csv['slope'] = sip_csv['rm'].diff()
#drop the first nrec samples
sip_csv = sip_csv.iloc[(nrec+1):, ]


lowtrigger = 0.007
hightrigger = 0.011

#See if it passes the low trigger
sip_csv["rm"] =  sip_csv['atn'].rolling(nrec, min_periods=23).mean()
sip_csv['slope'] = sip_csv['rm'].diff()
sip_csv["triggerNrecslope"] = np.where(sip_csv['slope'] >= lowtrigger, 'LowTrigger', 'WaitSlope')

nsamples_6weeks = 32
if (len(sip_csv) > nsamples_6weeks):
    #find the rolling rate low triggers in past ~1.5 months
    sip_csv['low_trigger_rate'] = (sip_csv['triggerNrecslope'] == 'LowTrigger').rolling(nsamples_6weeks, min_periods=2).sum()

    #Line to help keep tabs on whether the switch has been flipped and we're now using the high trigger

    sip_csv['max_rate'] = sip_csv['low_trigger_rate'].cummax()

    try:
        # Ensure 'max_rate' column is not empty and the values are valid
        if 'max_rate' in sip_csv.columns and not sip_csv['max_rate'].isnull().all():
            # Apply condition element-wise to the 'max_rate' column
            sip_csv["Fire_slope_trigger"] = np.where(
                sip_csv['max_rate'].abs() > 3,
                np.where(sip_csv['slope'] >= hightrigger, 'Fire', 'Wait'),
                np.where(sip_csv['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'] * 30
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 = sip_csv
seq_to_match = matchlist

df = check_sequence(df, 'Fire_slope_trigger', seq_to_match)
df['match'] = df['match'].astype(str)
df["Fire_anyway"] = np.where(df['match'].str.contains('T'), 'Fire', 'Wait')

if (len(sip_csv) > nsamples_6weeks):
    df['SendTrigger'] = np.where((df['Fire_anyway'] == 'Fire') |
                        (df['Fire_slope_trigger'] =='Fire'), 'SendTrigger', 'Wait')
    result = np.where((df['Fire_anyway'] == 'Fire') |
             (df['Fire_slope_trigger'] =='Fire'), 'Event detected', 'Wait')
else:
    df['SendTrigger'] = np.where((df['Fire_anyway'] == 'Fire') |
                        False, 'SendTrigger', 'Wait')
    result = np.where((df['Fire_anyway'] == 'Fire') |
             False, 'Event detected', 'Wait')

# Emit result
if (len(result) > 0):
    print(result[len(result)-1])
    
