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

def plot_csv(file_path):
    df = pd.read_csv(file_path, decimal=',', sep=';')
    plt.plot(df.iloc[1:, 0], df.iloc[1:, 1], linewidth=0.5)
    plt.title(file_path)
    plt.xlabel(df.columns[0])
    plt.ylabel(df.columns[1])
    plt.grid(True)
    plt.show()

def shift_x_to_zero(input_file, output_file):
    df = pd.read_csv(input_file, decimal=',', sep=';')
    df.iloc[1:, 0] = df.iloc[1:, 0] - df.iloc[1:, 0].iloc[0]
    df.to_csv(output_file, index=False, decimal=',', sep=';')

def normalize_current(input_path, output_path, frac_avg=0.05):
    df = pd.read_csv(input_path, sep=';', decimal=',')
    t = df.iloc[:, 0].values
    I = df.iloc[:, 1].values
    n = len(I)
    n_avg = max(1, int(n * frac_avg))
    first_mean = np.mean(I[:n_avg])
    last_mean = np.mean(I[-n_avg:])
    if first_mean > last_mean:
        I_max = first_mean
        I_min = last_mean
    else:
        I_max = last_mean
        I_min = first_mean
    I_norm = 1-(I - I_min)/abs(I_max - I_min)
    out = pd.DataFrame({'Time': t, 'I_norm': I_norm})
    out.to_csv(output_path, sep=';', decimal=',', index=False)


files = ["MEM_16M_B.csv", "MEM_1M_B.csv", "MEM_4M_B.csv", "MRZ_2.178_16.7M_B.csv", "MRZ_2.178_5.6M_B.csv", "MRZ_2.178_50M_B.csv", "MEM_16M_R.csv", "MEM_1M_R.csv", "MEM_4M_R.csv", "MRZ_2.178_16.7M_R.csv", "MRZ_2.178_5.6M_R.csv", "MRZ_2.178_50M_R.csv"]

dir1 = "data/raw/"
dir2 = "data/processed/"

for file in files:
    shift_x_to_zero(dir1 + file, dir2 + file)
    normalize_current(dir2 + file, dir2 + file)
    plot_csv(dir2 + file)
    # plot_csv(dir1 + file)