# Import necessary libraries
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter
import os

# Define the directory for saving plots
save_dir = 'output'
os.makedirs(save_dir, exist_ok=True)  # Ensure the directory exists

# Load the CSV file with UTF-8 encoding and semicolon delimiter
data = pd.read_csv('hydrochimie_lucie.csv', delimiter=';', encoding='utf-8')

# Replace comma with period in all columns to ensure numeric parsing
data = data.applymap(lambda x: str(x).replace(',', '.').strip() if isinstance(x, str) else x)

# Ensure the 'Date' column is in datetime format
data['Date'] = pd.to_datetime(data['Date'], dayfirst=True, errors='coerce')

# Convert all parameter columns to numeric, coercing any errors to NaN
parameters = data.columns[9:]  # Adjust if parameters are in different columns
for param in parameters:
    data[param] = pd.to_numeric(data[param], errors='coerce')

# List of unique sampling points
sampling_points = data['Nom'].unique()

# Determine the global y-axis limits for each parameter and the global x-axis limits
y_limits = {}
for param in parameters:
    min_val, max_val = data[param].min(), data[param].max()
    if min_val == max_val:
        y_limits[param] = (min_val - 0.1, max_val + 0.1)
    else:
        y_limits[param] = (min_val, max_val)

x_limit = (data['Date'].min(), data['Date'].max())

# Loop through each sampling point and parameter to generate plots
for point in sampling_points:
    # Filter data for the current sampling point and sort by date
    point_data = data[data['Nom'] == point].sort_values(by='Date')
    
    # Plot each parameter over time
    for param in parameters:
        plt.figure(figsize=(10, 6))
        plt.plot(point_data['Date'], point_data[param], 'o-', label=param)
        plt.xlabel('Date')
        plt.ylabel(param)
        plt.title(f'{param} Evolution at {point}')
        plt.gca().xaxis.set_major_formatter(DateFormatter('%d/%m/%Y'))
        plt.xticks(rotation=45)
        plt.ylim(y_limits[param])  # Set consistent y-axis limits for the parameter
        plt.xlim(x_limit)  # Set consistent x-axis limits for all plots
        plt.legend()
        plt.tight_layout()
        
        # Save the plot to the specified directory with safe filename
        filename = f"{param}_Evolution_at_{point}.svg".replace(" ", "_").replace("/", "_").replace("\\", "_")
        plt.savefig(os.path.join(save_dir, filename), format='svg', dpi=300)
        
        # plt.show()
        plt.close()  # Close the figure to free memory