import sys
from importlib import reload
sys.path.append('./')
import asotr
reload(asotr)
import matplotlib.pyplot as plt
from matplotlib import dates
import numpy as np
from datetime import timedelta

path = '../data/asotr/'
pict_name = '../plots/periods_profile/periods_profile_10042025.png'
channel = 'ch1'
asotr_kit = '01'
start_date = '24.04.2025 22:30:00'
end_date = '25.04.2025 02:00:00'
# start_date = '06.01.2025 22:40:00'
# end_date = '21.01.2025 01:20:00'
shift = False 

raw_data, data_dict = asotr.get_data(path, asotr_kit, start_date, end_date, 'minutes')

data1 = data_dict['temp'][channel]
time1 = data_dict['time_temp']

periods_t, periods, _ = asotr.find_periods(time1, data1, shift_flag=False, peaks='min')

_, _, peaks = asotr.find_periods(time1, data1, shift_flag=False, peaks='max')

peaks_forecast = asotr.get_peak_temp_forecast(time1.iloc[peaks[0]], 1000)

delta_sec = []
for idx, elem in enumerate(peaks):
    if idx > 0:
        print(f'peak____: {time1.iloc[elem]}')
        print(f'forecast: {peaks_forecast[idx-1]}')
        delta = time1.iloc[elem] - peaks_forecast[idx-1]
        delta_sec.append(delta.total_seconds())

time_, periods_ = asotr.get_signal_profile_corr(time1, data1, periods[0], shift, peak_height=0.7)
print(f'Найдено {len(periods_)} периодов.')

ox_dtime_format = "%H:%M:%S"
fig, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize=(14, 10))

date_formatter = dates.DateFormatter(ox_dtime_format)
ax1.xaxis.set_major_formatter(date_formatter)

ax1.plot(time1, data1)
for elem in peaks:
    ax1.axvline(x = time1.iloc[elem], color='r', linewidth=0.5)
    
ax1.set_title(f'Температура на орбите: АСОТР{asotr_kit}, канал {channel[2]}')

for idx, period in enumerate(periods_):
    ax2.plot(np.arange(len(period)), period, label=f'период {idx}')

ax2.set_title('Профиль изменения температуры АСОТР по периоду')

delta = []
for elem in periods_:
    delta1 = elem.values - periods[0].values
    delta.append(delta1)
    
for idx, elem in enumerate(delta):
    if idx == len(delta) - 1:
        ax3.plot(elem, label=f'период {idx}', marker='|', linewidth=2)
    elif idx == len(delta)//2:
        ax3.plot(elem, label=f'период {idx}', marker='^', linewidth=2)
    elif idx == 1:
        ax3.plot(elem, label=f'период {idx}', marker='o', linewidth=2)
    elif idx > 0:
        ax3.plot(elem, label=f'период {idx}')

ax3.set_title(r'$\Delta$$T_i$ = $T_i$ - $T_1$')
ax1.set_ylabel('Температура, $^\circ$C')
ax2.set_ylabel('Температура, $^\circ$C')
ax3.set_ylabel(r'$\Delta$$T_i$, $^\circ$C')
ax3.set_xlabel("Время, мин.")
ax1.grid(True)
ax2.grid(True)
ax3.grid(True)
ax2.legend()
ax3.legend()
fig.savefig(pict_name)
plt.show()
