import json
from docxtpl import DocxTemplate
import subprocess
import smtplib
from email.message import EmailMessage
import os
from pathlib import Path
from datetime import datetime

# === Étape 1 : Chargement des données JSON ===
json_path = Path("donnees.json")
if not json_path.exists():
    print("❌ Fichier donnees.json introuvable.")
    exit(1)

with open(json_path, "r", encoding="utf-8") as file:
    data = json.load(file)

# === Étape 2 : Calcul du score total ===
questions = [f"Q{i}" for i in range(1, 11)]
score = sum(1 for q in questions if data.get(q, "").lower() == "oui")
data["Score_total"] = score

# === Étape 3 : Choix du modèle Word ===
if score <= 3:
    modele = "modeles/modele_faible.docx"
    data["Niveau_de_maturite"] = "Faible"
    data["Recommandation"] = "Vous avez un fort potentiel d'amélioration. Un diagnostic complet et un plan d'action RH + IA sont recommandés."
elif score <= 7:
    modele = "modeles/modele_intermediaire.docx"
    data["Niveau_de_maturite"] = "Intermédiaire"
    data["Recommandation"] = "Votre agence a déjà des bases solides. Un accompagnement ciblé vous permettra de progresser rapidement."
else:
    modele = "modeles/modele_avancé.docx"
    data["Niveau_de_maturite"] = "Avancé"
    data["Recommandation"] = "Félicitations ! Vous avez une maturité avancée. Continuez la veille et les optimisations."

# === Étape 4 : Génération du Word ===
Path("output").mkdir(exist_ok=True)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
word_file = f"output/rapport_{data['Nom_agence']}_{timestamp}.docx"
pdf_file = word_file.replace(".docx", ".pdf")

doc = DocxTemplate(modele)
doc.render(data)
doc.save(word_file)

# === Étape 5 : Conversion DOCX > PDF avec LibreOffice ===
try:
    subprocess.run([
        "libreoffice",
        "--headless",
        "--convert-to", "pdf",
        "--outdir", "output",
        word_file
    ], check=True)
except Exception as e:
    print("❌ Erreur de conversion PDF :", e)
    exit(1)

# === Étape 6 : Envoi Email ===
smtp_server = "mail.360performance.fr"
smtp_port = 587
smtp_email = "c.bruneau@360performance.fr"
smtp_password = "Lia_emilie44600"

msg = EmailMessage()
msg["From"] = smtp_email
msg["To"] = data["Email"]
msg["Subject"] = f"Votre rapport personnalisé - {data['Nom_agence']}"

html = f"""
<html>
<body>
    <p>Bonjour {data['Prenom']} {data['Nom']},</p>
    <p>Merci d’avoir complété notre auto-diagnostic <strong>RH & Digital</strong>.</p>
    <ul style='list-style:none;'>
        <li>&#128202; <strong>Score global :</strong> {score * 10}%</li>
        <li>&#128200; <strong>Niveau de maturité :</strong> {data['Niveau_de_maturite']}</li>
        <li>&#128221; <strong>Recommandation :</strong> {data['Recommandation']}</li>
    </ul>
    <p>Votre rapport PDF est en pièce jointe.</p>
</body>
</html>
"""

msg.add_alternative(html, subtype='html')

with open(pdf_file, "rb") as f:
    msg.add_attachment(f.read(), maintype="application", subtype="pdf", filename=os.path.basename(pdf_file))

try:
    with smtplib.SMTP(smtp_server, smtp_port) as server:
        server.starttls()
        server.login(smtp_email, smtp_password)
        server.send_message(msg)
    print("✅ Rapport généré et envoyé à :", data["Email"])
except Exception as e:
    print("❌ Erreur lors de l'envoi de l'email :", e)

