# -*- coding: utf-8 -*-
"""
Created on Tue Nov 19 15:45:25 2024

@author: chuffard
"""
import numpy as np

import pandas as pd

#Rate_threshold =  If it goes through 2 cups in one month, then bump it up. 

SES_RAW = pd.read_csv('G:/Deployments/MARS-2024/SES_out_atn.csv')

SES_RAW['datetemp'] = SES_RAW['file_name'].str.split('_').str[-1]
SES_RAW['collect_time'] = SES_RAW['file_name'].str.split('_').str[-3]
#year month date
SES_RAW['YMD'] = SES_RAW['datetemp'].str.split('-').str[-2]
SES_RAW['YMD'] = SES_RAW['YMD'].astype(int)

#Year is YY but want YYYY. Add "20" to left of integer by adding 20000000
SES_RAW['YMD2'] = SES_RAW['YMD']+20000000
SES_RAW['YMD2'] = SES_RAW['YMD2'].astype(str)
SES_RAW['year'] =SES_RAW["YMD2"].str[:4] 
SES_RAW['month'] = SES_RAW["YMD2"].str[4:6] 
SES_RAW['day']=  SES_RAW["YMD2"].str[6:]

SES_RAW['HMS'] = SES_RAW['datetemp'].str.split('-').str[-1]
#remove .jpg
SES_RAW["HMS"] = SES_RAW["HMS"].str[:-4] 
#can't convert to int because removes zeroes on left

SES_RAW['hour'] =SES_RAW["HMS"].str[:2] 
SES_RAW['minutes'] = SES_RAW["HMS"].str[2:4] 
SES_RAW['second']=  SES_RAW["HMS"].str[4:]

SES_RAW['datetime'] = pd.to_datetime(SES_RAW[['year','month','day', 'hour', 'minutes']], format="%Y-%m-%d %H:%M")

#sort by datetime
SES_RAW_sorted = SES_RAW.sort_values(by='datetime')

#find the rolling mean= 150 samples, minimum sample size 23.
SES_RAW_sorted['rm150'] = SES_RAW_sorted['atn'].rolling(150, min_periods=23).mean()


#Find the difference (slope)
SES_RAW_sorted['Slope_rm_150'] = SES_RAW_sorted['rm150'].diff()

#drop the first 150 samples
SES_RAW_sorted = SES_RAW_sorted.iloc[151:, ]

#start with low trigger

lowtrigger = 0.007
hightrigger = 0.011

#See if it passes the low trigger
SES_RAW_sorted["trigger150slope"] = np.where(SES_RAW_sorted['Slope_rm_150'] >= lowtrigger, 'LowTrigger', 'WaitSlope')

#find the rolling rate low triggers in past 635 samples.
SES_RAW_sorted['low_trigger_rate'] = (SES_RAW_sorted['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
SES_RAW_sorted['max_rate'] = SES_RAW_sorted['low_trigger_rate'].cummax()

try:
    # Ensure 'max_rate' column is not empty and the values are valid
    if 'max_rate' in SES_RAW_sorted.columns and not SES_RAW_sorted['max_rate'].isnull().all():
        # Apply condition element-wise to the 'max_rate' column
        SES_RAW_sorted["Fire_trigger"] = np.where(
            SES_RAW_sorted['max_rate'].abs() > 3,
            np.where(SES_RAW_sorted['Slope_rm_150'] >= hightrigger, 'Fire', 'Wait'),
            np.where(SES_RAW_sorted['Slope_rm_150'] >= 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}")


SES_RAW_sorted.to_csv("G:/Deployments/MARS2024B-2025/SES_dataprep.csv")












