#!/usr/bin/env python3
"""
Installe les signatures Elevaseo (FR + EN) dans Apple Mail.

CE QUE FAIT LE SCRIPT
  - localise ~/Library/Mail/V<plus haut>/MailData/Signatures/
  - trouve les .mailsignature contenant les marqueurs ELEVASEO_FR / ELEVASEO_EN
    (les placeholders que TU crees dans Mail, voir PREREQUIS)
  - remplace le corps <body>...</body> par notre HTML, en preservant les
    en-tetes du fichier (Content-Type, Message-Id, Mime-Version...)
  - force le charset UTF-8 (accents é à...)
  - verrouille le fichier (chflags uchg = case "Verrouille" du Finder) pour
    que Mail ne l'ecrase pas

PREREQUIS (a faire UNE fois, dans cet ordre)
  1. Donner a Ghostty l'acces "Disque complet" :
       Reglages Systeme > Confidentialite et securite > Acces complet au disque
       -> ajouter / activer Ghostty, puis RELANCER Ghostty.
  2. Dans Mail : Reglages > Signatures, creer DEUX signatures :
       - nom "Elevaseo FR", corps = le texte exact :  ELEVASEO_FR
       - nom "Elevaseo EN", corps = le texte exact :  ELEVASEO_EN
     Les glisser sur le bon compte. Puis QUITTER Mail (Cmd+Q) entierement.
  3. Lancer ce script :  python3 install_apple_mail_signatures.py

Relance Mail apres : les signatures HTML doivent s'afficher.
"""
import os, re, sys, glob, subprocess

HERE = os.path.dirname(os.path.abspath(__file__))

# marqueur placeholder  ->  fichier source HTML
SOURCES = {
    "ELEVASEO_FR": os.path.join(HERE, "signature_email.html"),
    "ELEVASEO_EN": os.path.join(HERE, "signature_email_en.html"),
}


def extract_table(html_path):
    """Recupere uniquement le bloc <table>...</table> du fichier signature."""
    html = open(html_path, encoding="utf-8").read()
    m = re.search(r"<table\b.*?</table>", html, re.DOTALL | re.IGNORECASE)
    if not m:
        sys.exit(f"[ERREUR] aucun <table> trouve dans {html_path}")
    return m.group(0).strip()


def find_signatures_dir():
    base = os.path.expanduser("~/Library/Mail")
    versions = sorted(glob.glob(os.path.join(base, "V*")),
                      key=lambda p: int(re.sub(r"\D", "", os.path.basename(p)) or 0))
    for v in reversed(versions):
        d = os.path.join(v, "MailData", "Signatures")
        if os.path.isdir(d):
            return d
    sys.exit("[ERREUR] dossier Signatures introuvable sous ~/Library/Mail/V*")


def preflight(sig_dir):
    try:
        os.listdir(sig_dir)
    except PermissionError:
        sys.exit(
            "[BLOQUE] Acces refuse a " + sig_dir + "\n"
            "  -> Ghostty n'a pas 'Acces complet au disque'.\n"
            "  Reglages Systeme > Confidentialite et securite > Acces complet\n"
            "  au disque : ajoute/active Ghostty, RELANCE Ghostty, puis relance\n"
            "  ce script."
        )
    # Mail doit etre quitte
    r = subprocess.run(["pgrep", "-x", "Mail"], capture_output=True, text=True)
    if r.stdout.strip():
        sys.exit("[ARRET] Mail est ouvert. Quitte-le (Cmd+Q) puis relance le script.")


def inject(path, table_html):
    raw = open(path, "r", encoding="utf-8", errors="replace").read()
    lo = raw.lower()
    i = lo.find("<body")
    if i == -1:
        # pas encore de structure html (placeholder brut) : on en cree une
        head = raw.split("\n\n", 1)[0]
        new = head + "\n\n<html><head><meta http-equiv=\"Content-Type\" " \
              "content=\"text/html; charset=utf-8\"></head><body>\n" \
              + table_html + "\n</body></html>\n"
    else:
        j = raw.find(">", i)                # fin de la balise <body ...>
        k = lo.rfind("</body>")
        new = raw[:j + 1] + "\n" + table_html + "\n" + raw[k:]
    # charset UTF-8
    new = re.sub(r"charset=us-ascii", "charset=utf-8", new, flags=re.IGNORECASE)
    # deverrouiller -> ecrire -> reverrouiller
    subprocess.run(["chflags", "nouchg", path])
    with open(path, "w", encoding="utf-8") as f:
        f.write(new)
    subprocess.run(["chflags", "uchg", path])


def main():
    sig_dir = find_signatures_dir()
    print(f"[i] Signatures : {sig_dir}")
    preflight(sig_dir)

    tables = {marker: extract_table(src) for marker, src in SOURCES.items()}
    files = glob.glob(os.path.join(sig_dir, "*.mailsignature"))
    if not files:
        sys.exit("[ERREUR] aucun .mailsignature. As-tu cree les placeholders "
                 "dans Mail puis quitte Mail ?")

    done = {}
    for path in files:
        try:
            content = open(path, "r", encoding="utf-8", errors="replace").read()
        except PermissionError:
            continue
        for marker, table in tables.items():
            if marker in content and marker not in done:
                inject(path, table)
                done[marker] = os.path.basename(path)
                print(f"[OK] {marker}  ->  {os.path.basename(path)} (verrouille)")

    missing = [m for m in SOURCES if m not in done]
    if missing:
        print("\n[ATTENTION] marqueurs non trouves : " + ", ".join(missing))
        print("  Cree dans Mail une signature dont le CORPS = ce texte exact,")
        print("  quitte Mail, puis relance le script.")
    else:
        print("\nTermine. Relance Mail : les signatures HTML doivent apparaitre.")


if __name__ == "__main__":
    main()
