"""Send the SANEF Qualys V3 docx to khalid.moutaouakil-ext@sanef.com via Gmail SMTP."""
import os
import smtplib
import ssl
from email.message import EmailMessage
from pathlib import Path

SENDER = "kalid.moutaouakil@gmail.com"
RECIPIENT = "khalid.moutaouakil-ext@sanef.com"
ATTACHMENTS = [
    (Path(r"C:\Claude\sanef\QL\docs\SANEF_Qualys_V3_Resume_Vigilance.docx"),
     "vnd.openxmlformats-officedocument.wordprocessingml.document"),
    (Path(r"C:\Claude\sanef\QL\docs\SANEF_Qualys_Tags_V3_RuleTypes_v2.xlsx"),
     "vnd.openxmlformats-officedocument.spreadsheetml.sheet"),
]

password = os.environ.get("GMAIL_APP_PASSWORD")
if not password:
    raise SystemExit("GMAIL_APP_PASSWORD non defini dans l'environnement")
password = password.replace(" ", "")

msg = EmailMessage()
msg["From"] = SENDER
msg["To"] = RECIPIENT
msg["Subject"] = "SANEF Qualys V3 - Resume d'execution + points de vigilance (mise a jour)"
msg.set_content(
    "Bonjour Khalid,\n\n"
    "En piece jointe le resume d'execution mis a jour de la taxonomie Qualys V3.\n\n"
    "Modifications par rapport a la version precedente :\n"
    "  - Renommage TYP -> EQT (Equipement) : EQT-SRV, EQT-VIR, EQT-SWI\n"
    "  - Correction ENV-TST : exclusion des postes Superviseur Peage (svp*),\n"
    "    le tag passe de ~180 a 83 assets coherents\n"
    "  - Meme correction appliquee a EQT-SRV (and not asset.name:svp*)\n"
    "  - Ajout d'une decouverte technique en section 1.2 sur le conflit svp*\n"
    "  - Section 4 Annexes retiree (la reference complete est dans le xlsx joint)\n\n"
    "Egalement en piece jointe : SANEF_Qualys_Tags_V3_RuleTypes_v2.xlsx\n"
    "(reference complete : 23 tags dynamiques + 7 statiques + prefixes manuels)\n\n"
    "Le document conserve les sections 2 (points de vigilance) et 3 (TODO).\n\n"
    "Cordialement,\n"
    "SECOPS\n"
)

for path, subtype in ATTACHMENTS:
    if not path.exists():
        raise SystemExit(f"Fichier introuvable : {path}")
    with path.open("rb") as f:
        msg.add_attachment(
            f.read(),
            maintype="application",
            subtype=subtype,
            filename=path.name,
        )

ctx = ssl.create_default_context()
with smtplib.SMTP("smtp.gmail.com", 587, timeout=30) as s:
    s.ehlo()
    s.starttls(context=ctx)
    s.ehlo()
    s.login(SENDER, password)
    s.send_message(msg)

for p, _ in ATTACHMENTS:
    print(f"  - {p.name} ({p.stat().st_size} bytes)")
print(f"Mail envoye a {RECIPIENT}")
