import os, shutil, pandas as pd, numpy as np, smtplib
from openpyxl import Workbook
from email.message import EmailMessage

# Configuration
INPUT_DIR = 'MESURES_TP'
EMAIL_SENDER = 'etudiant1@univ.com'
EMAIL_RECEIVER = 'etudiant2@univ.com'

print("=== AUTOMATISATION TP ===")

# 1. Analyse
fichiers = [f for f in os.listdir(INPUT_DIR) if f.endswith('.csv')]
print(f"📁 {len(fichiers)} fichiers analysés")

# 2. Rapport
results = []
for f in fichiers:
    df = pd.read_csv(os.path.join(INPUT_DIR, f))
    Vout = df['Tension_sortie (V)']
    results.append({'Fichier': f, 'V_moy': round(np.mean(Vout), 2)})

wb = Workbook()
ws = wb.active
ws.title = "Resultats"
for r in results: ws.append([r['Fichier'], r['V_moy']])
wb.save('Rapport.xlsx')
print("✅ Rapport généré")

# 3. Email
envoyer = input("Envoyer par email? (o/n): ").lower()
if envoyer == 'o':
    pwd_type = input("Mot de passe [1=normal, 2=application]: ")
    password = input("Votre mot de passe: ")
    
    msg = EmailMessage()
    msg['Subject'] = 'Rapport TP'
    msg['From'] = EMAIL_SENDER
    msg['To'] = EMAIL_RECEIVER
    msg.set_content("Rapport joint")
    
    with open('Rapport.xlsx', 'rb') as f:
        msg.add_attachment(f.read(), maintype='application', 
                         subtype='vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                         filename='Rapport.xlsx')
    
    try:
        with smtplib.SMTP_SSL('smtp.gmail.com', 465) as s:
            s.login(EMAIL_SENDER, password)
            s.send_message(msg)
        print("✅ Email envoyé!")
    except:
        print("❌ Échec envoi")

print("=== FIN ===")