import matplotlib
matplotlib.use('Agg')  # nastaví neinteraktivní backend před načtením pyplot

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import os

# Parametry
channels = [f'ch{i}.csv' for i in range(1, 13)]
fig, axs = plt.subplots(6, 2, figsize=(12, 10), sharex=True)
fig.suptitle("GOLEM Shot")
axs = np.array(axs)  # zajistí kompatibilitu indexování

# Rozdeleni na R a L
axs_R = [axs[i][0] for i in range(6)]
axs_L = [axs[i][1] for i in range(6)]
group_R = channels[:6]  # ch1-ch6
group_L = channels[6:]  # ch7-ch12

# Funkce pro vykresleni skupiny
def plot_group(axs, group, ref_file, scale_std, labels_prefix):
    # Nacteni referencniho signalu
    ref_data = pd.read_csv(ref_file, header=None)
    t_ref, y_ref = ref_data[0], ref_data[1]
    mean = y_ref.mean()
    std = y_ref.std()
    ymin = mean - scale_std * std
    ymax = mean + scale_std * std

    for ax, fname, label in zip(axs, group, range(1, 7)):
        if not os.path.exists(fname):
            continue
        data = pd.read_csv(fname, header=None)
        t, y = data[0].to_numpy(), data[1].to_numpy()
        ax.plot(t * 1000, y, linestyle='-', linewidth=0.8)
        ax.set_ylabel(f"{labels_prefix}{label}")
        ax.set_ylim(ymin, ymax)
        ax.set_yticks([0, round(ymax, 2)])
        ax.grid(True, linestyle=':', linewidth=0.5)

# Vykresleni obou skupin
plot_group(axs_R, group_R, 'ch1.csv', 3.0, 'R')
plot_group(axs_L, group_L, 'ch7.csv', 3.0, 'L')

# X osa
for ax in axs_R[-1:] + axs_L[-1:]:
    ax.set_xlabel("Time [ms]")
    ax.set_xticks([10, 20, 30, 40])

plt.tight_layout(rect=[0, 0, 1, 0.97])
plt.savefig("ScreenShotAll.png", dpi=150)
# plt.show()  # disabled to suppress display

