#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
from datetime import datetime

# fichier de données
fichier = 'data/temperatures_38.25_96.75.txt'

# lecture des colonnes : date (str), decimal date (float32), temp (float32)
time, temp = np.loadtxt(fichier, delimiter=',', usecols=(1,2), dtype=np.float32, unpack=True)
dates_str = np.loadtxt(fichier, delimiter=',', usecols=(0), dtype='str')

t_mean =  np.nanmean(temp)
print('Min T: {:0.3f}˚, Max T: {:0.3f}˚'.format(np.nanmin(temp), np.nanmax(temp)))
print('Mean T>0: {:0.3f}˚, Mean T<0: {:0.3f}˚'.format(np.nanmean(temp[temp>0]), np.nanmean(temp[temp<0])))

# températures à 11h
temp_11h = temp[::2]
print('Mean T at 11am: {:0.3f}˚'.format(np.nanmean(temp_11h)))
print('STD T at 11am: {:0.3f}˚'.format(np.std(temp_11h)))

# dates_str contient les dates lues en format texte
dates = [datetime.strptime(d, '%Y-%m-%d %H:%M:%S') for d in dates_str]
print([d.month for d in dates])

# calcul des valeurs mensuels
months = np.array([d.month for d in dates])

mean_months = np.zeros((12))
count = np.zeros((12))
# compute mean of each months
for i in range(len(temp)):
    month_index = int(months[i]) - 1   # transformer le mois (1-12) en indice (0-11)
    mean_months[month_index] += temp[i]  # ajouter la température à la somme
    count[month_index] += 1             # incrémenter le compteur
mean_months = mean_months / count
print("Moyenne par mois :", mean_months)

# inversion
N = len(temp)
M = 4
G = np.zeros((N, M))
G[:,0] = np.cos(2 * np.pi * time)   # cos
G[:,1] = np.sin(2 * np.pi * time)   # sin
G[:,2] = time                       # tendance linéaire
G[:,3] = 1                          # constante (offset / moyenne)

m, residuals, rank, s = np.linalg.lstsq(G, temp, rcond=None)  # moindres carrés
print('A: ', m[0], 'B: ', m[1], 'C: ', m[2], 'D: ', m[3])

# paramètres physiques
Amp = np.sqrt(m[0]**2 + m[1]**2)          # amplitude
Phi = np.arctan2(m[1], m[0])              # phase
V = m[2]                                  # pente (trend)
Offset = m[3]                             # moyenne


# plot data
fig = plt.figure(0, figsize=(16, 9))

# --- 1. Série temporelle ---
ax1 = fig.add_subplot(2, 2, 1)
ax1.plot(dates, temp, '-bo', ms=.5, lw=.1,
         label='Moyenne T˚:{:0.3}˚'.format(t_mean), rasterized=True)
ax1.plot(dates, np.dot(G,m), '-r', lw=2.,
             label='Amp: {0:.1f}˚, Phi: {1:.2f}, V: {2:.3f}˚/an'.format(Amp, Phi, V))
ax1.set_xlabel('Temps')
ax1.set_ylabel('Temperature (˚C)')
ax1.legend(loc='best')
ax1.grid(True)
plt.setp(ax1.get_xticklabels(), rotation=45)

# --- 2. Températures selon le mois (x fraction de l’année) ---
ax2 = fig.add_subplot(2, 2, 2)
ax2.set_xticks(np.arange(0, 1, 1. / 12))
ax2.plot(np.mod(time, 1), temp, 'bo', ms=.5, lw=.1,
         label='Moyenne T˚ en Aout :{:0.3}˚'.format(mean_months[8]), rasterized=True)
ax2.set_xlabel('Mois')
ax2.set_ylabel('Temperature (˚C)')
ax2.set_xlim([0, 1])
ax2.set_xticklabels(["Jan", "Fév", "Mar", "Avr", "Mai", "Juin",
                     "Juil", "Aoû", "Sep", "Oct", "Nov", "Déc"])
ax2.legend(loc='best')
ax2.grid(True)

# --- 3. Moyenne par mois ---
if mean_months is not None:
    ax3 = fig.add_subplot(2, 2, 3)
    ax3.bar(range(1, 13), mean_months, color="skyblue", edgecolor="k")
    ax3.set_xlabel("Mois")
    ax3.set_ylabel("Température moyenne (°C)")
    ax3.set_title("Température moyenne par mois")
    ax3.set_xticks(range(1, 13))
    ax3.set_xticklabels(["Jan", "Fév", "Mar", "Avr", "Mai", "Juin",
                         "Juil", "Aoû", "Sep", "Oct", "Nov", "Déc"])
    ax3.grid(axis="y", linestyle="--", alpha=0.7)

# --- 4. Histogramme ---
ax4 = fig.add_subplot(2, 2, 4)
ax4.hist(temp, bins=30, color="salmon", edgecolor="k", alpha=0.7)
ax4.set_xlabel("Température (°C)")
ax4.set_ylabel("Fréquence")
ax4.set_title("Distribution des températures")
ax4.grid(axis="y", linestyle="--", alpha=0.7)

fig.savefig('plot_temperatures.pdf', format='PDF')
plt.tight_layout()
plt.show()