#!/usr/bin/env python3
"""
Build statique de votre-fiche-google.fr
- pages/**/*.html  (front-matter entre --- ... --- puis HTML du contenu)
- assets/          copiés tels quels
- dist/            site final, à déposer en FTP ou sur Netlify

Usage : python3 build.py
"""
import os, re, json, shutil, datetime, html, hashlib

ROOT = os.path.dirname(os.path.abspath(__file__))
SRC = os.path.join(ROOT, "pages")
DIST = os.path.join(ROOT, "dist")

# ------------------------------------------------------------------ CONFIG
# Valeurs par défaut. Elles sont écrasées par config.json (modifiable depuis le back-office admin.py).
CONFIG = {
    "SITE_URL": "https://votre-fiche-google.fr",
    "SITE_NAME": "votre-fiche-google.fr",
    "TAGLINE": "Plus de visibilité, plus de clients.",
    # --- SEO global (JSON-LD Organization, titres, robots) — éditable dans Réglages › SEO
    "ORG_NAME": "", "ORG_LOGO": "", "ORG_TEL": "",         # vides = valeurs déduites (nom du site, logo détecté, TEL)
    "ORG_STREET": "", "ORG_POSTAL": "", "ORG_CITY": "", "ORG_REGION": "", "ORG_COUNTRY": "FR",
    "TITLE_SUFFIX": "",                                     # suffixe des titres des NOUVELLES pages (vide = " | " + nom du site)
    "ROBOTS_TXT": "",                                       # contenu robots.txt de PRODUCTION (vide = défaut Allow + Sitemap)
    "WEB3FORMS_KEY": "VOTRE_CLE_WEB3FORMS",       # https://web3forms.com (gratuit)
    "CALENDLY_URL": "https://calendly.com/agence-beecom",
    "EMAIL": "contact@agence-beecom.fr",
    "TEL": "05 59 03 35 62", "TEL_HREF": "+33559033562",   # numéro public (7j/7)
    "ADDRESS": "Saint-Jean-d'Illac (33) — Métropole de Bordeaux",
    "AGENCY_URL": "https://www.agence-communication-beecom.fr/",
    "GA_ID": "",                                   # Google Analytics 4 (optionnel)
    "MATOMO_URL": "", "MATOMO_SITE_ID": "",        # ex. https://stats.agence-beecom.fr/ et 1
    "BLOG_BASE": "", "FAVICON": "", "MATOMO_TOKEN": "",
    "DEFAULT_OG": "/assets/img/og-default.jpg", "DEFAULT_ARTICLE_IMG": "/assets/img/guide/_default.webp",
    "FTP_HOST": "", "FTP_USER": "", "FTP_PASS": "", "FTP_DIR": "/www",   # publication depuis admin.py (optionnel)
    "ENV": "preprod",                              # preprod (noindex + mot de passe) | prod
    "PREPROD_URL": "https://preprod.votre-fiche-google.fr",
    "FTP_DIR_PREPROD": "/preprod.votre-fiche-google.fr", "FTP_DIR_PROD": "/votre-fiche-google.fr",
    "PREPROD_USER": "beecom", "PREPROD_PASS": "",  # protection par mot de passe de la préprod (vide = pas de protection)
    "PUBLISH_MODE": "",                            # "" = FTP (back-office local) · "copy" = copie directe (back-office hébergé sur le même serveur)
    "DOCROOT_PROD": "", "DOCROOT_PREPROD": "",     # chemins absolus des dossiers publics (mode copie), ex. /home/compte/votre-domaine.fr
    "SERVER_HOME": "",                             # ex. /home/beecom (chemin absolu du compte cPanel, visible dans cPanel > Informations générales)
    # --- Formulaires & e-mails (mode "php" = script sur l'hébergement, "web3forms" = service tiers)
    "FORM_MODE": "php",
    "PERF_OPTIMS": "true",   # optimisations PageSpeed à la génération (polices/Calendly non bloquants, srcset, fetchpriority) — "false" pour désactiver
    "SMTP_HOST": "", "SMTP_PORT": "465", "SMTP_USER": "", "SMTP_PASS": "",   # envoi SMTP authentifié (recommandé) ; vide = mail() de PHP
    "FORM_TO": "contact@agence-beecom.fr",          # destinataire(s) des demandes, séparés par des virgules
    "FORM_FROM": "noreply@votre-fiche-google.fr",   # expéditeur technique (une adresse du domaine hébergé)
    "FORM_FROM_NAME": "votre-fiche-google.fr",
    "FORM_SUBJECT_ADMIN": "Nouvelle demande : {sujet} — {nom}",
    "FORM_SUBJECT_CLIENT": "Votre demande est bien reçue — votre-fiche-google.fr",
    "FORM_CLIENT_MESSAGE": "Bonjour {nom},\n\nMerci pour votre demande ({sujet}). Nous l'avons bien reçue et nous revenons vers vous sous 24 h ouvrées.\n\nRécapitulatif :\n{recap}\n\nÀ très vite,\nL'équipe votre-fiche-google.fr — un service de l'agence Beecom'\n05 59 03 35 62 · contact@agence-beecom.fr",
    "FORM_ADMIN_MESSAGE": "Nouvelle demande reçue depuis {page} ({date}).\n\n{recap}\n\nRépondre : {email}",
    # --- Réseaux sociaux (vide = masqué)
    "SOCIAL_FACEBOOK": "", "SOCIAL_INSTAGRAM": "", "SOCIAL_LINKEDIN": "", "SOCIAL_YOUTUBE": "", "SOCIAL_TIKTOK": "", "SOCIAL_X": "",
    "INSTA_WIDGET": "",                              # code d'intégration d'un widget Instagram (Elfsight, LightWidget, SnapWidget…) → jeton {{INSTA_FEED}}
    # --- Cookies / consentement & codes tiers
    "CMP_SCRIPT": "",                                # code Sirdata CMP (balise <script> fournie par Sirdata) — injecté en premier dans <head>
    "HEAD_CODE": "",                                 # autre code à injecter dans <head> (GTM, vérification Search Console…)
    # --- Langues & traduction automatique (type WPML). LANGS vide = site monolingue. Format : fr:Français,en:English
    "LANGS": "",
    "LANG_SWITCH": "true",   # sélecteur de langue injecté automatiquement dans l'en-tête des sites importés
    "DEFAULT_LANG": "fr",
    "PALETTE": "",                    # couleurs nommées du site pour le panneau Apparence, ex. "Base:#f7f8fa,Blanc:#ffffff,Navy:#000b22" (vide = détection auto)
    "TRANSLATE_PROVIDER": "deepl",   # deepl | claude
    "DEEPL_KEY": "",                  # clé API DeepL (gratuite jusqu'à 500 000 caractères/mois — deepl.com/pro-api)
    "ANTHROPIC_KEY": "",              # clé API Anthropic (option, si fournisseur = claude)
    "TRANSLATE_MODEL": "",            # optionnel (défaut : claude-haiku)
}
CFG_PATH = os.path.join(ROOT, "config.json")
if os.path.exists(CFG_PATH):
    try: CONFIG.update({k: v for k, v in json.load(open(CFG_PATH, encoding="utf-8")).items() if v is not None})
    except Exception as e: print("⚠ config.json illisible :", e)
# ------------------------------------------------------------------ licence & empreinte Beecom
# Le moteur embarque la clé PUBLIQUE Beecom : il vérifie les licences, il ne peut pas en créer.
# licence.json (racine) lie cette copie du moteur à un domaine ; sans licence valide, le
# tableau de bord affiche un avertissement et la publication en PRODUCTION est refusée.
BEECOM_LICENCE_PUBKEY = "426158e2037fa36f61abcf378c838cba1edf5e42e7e130e6a038be251a492597"
def _edv(pk, msg, sig):
    """Vérification Ed25519 (implémentation de référence, pure Python — stdlib uniquement)."""
    try:
        import hashlib as _hl
        _P = 2**255 - 19; _Q = 2**252 + 27742317777372353535851937790883648493
        _D = -121665 * pow(121666, _P - 2, _P) % _P; _I = pow(2, (_P - 1) // 4, _P)
        def xr(y):
            xx = (y * y - 1) * pow(_D * y * y + 1, _P - 2, _P); x = pow(xx, (_P + 3) // 8, _P)
            if (x * x - xx) % _P: x = x * _I % _P
            return _P - x if x % 2 else x
        def dec(b):
            y = int.from_bytes(b, "little") & ((1 << 255) - 1); x = xr(y)
            if x & 1 != b[31] >> 7: x = _P - x
            if (-x * x + y * y - 1 - _D * x * x * y * y) % _P: raise ValueError
            return (x, y)
        def add(a, b):
            x1, y1 = a; x2, y2 = b
            return ((x1 * y2 + x2 * y1) * pow(1 + _D * x1 * x2 * y1 * y2, _P - 2, _P) % _P,
                    (y1 * y2 + x1 * x2) * pow(1 - _D * x1 * x2 * y1 * y2, _P - 2, _P) % _P)
        def mul(pt, e):
            q = (0, 1)
            while e:
                if e & 1: q = add(q, pt)
                pt = add(pt, pt); e >>= 1
            return q
        def enc(pt): return (pt[1] | ((pt[0] & 1) << 255)).to_bytes(32, "little")
        _by = 4 * pow(5, _P - 2, _P) % _P; _b = (xr(_by), _by)
        A = dec(pk); R = sig[:32]; S = int.from_bytes(sig[32:], "little")
        if S >= _Q: return False
        k = int.from_bytes(_hl.sha512(R + pk + msg).digest(), "little") % _Q
        return enc(mul(_b, S)) == enc(add(dec(R), mul(A, k)))
    except Exception:
        return False

def licence_status():
    """(ok, message) — licence.json doit être signé par Beecom et correspondre au domaine du site."""
    host = re.sub(r"^https?://", "", CONFIG.get("SITE_URL", "")).split("/")[0].lower()
    if not host or "changez-moi" in host:
        return False, "URL publique non renseignée (Réglages) : licence non vérifiable."
    lp = os.path.join(ROOT, "licence.json")
    if not os.path.exists(lp):
        return False, f"Aucune licence pour {host} — fichier licence.json absent. Contactez Beecom."
    try:
        lic = json.load(open(lp, encoding="utf-8"))
        dom = (lic.get("domain") or "").lower().strip()
        msg = f"{dom}|{lic.get('licensee', '')}|{lic.get('issued', '')}".encode()
        if not _edv(bytes.fromhex(BEECOM_LICENCE_PUBKEY), msg, bytes.fromhex(lic.get("sig", ""))):
            return False, "Licence invalide (signature incorrecte). Contactez Beecom."
        if not (host == dom or host.endswith("." + dom) or dom in host):
            return False, f"Licence délivrée pour {dom}, site configuré sur {host}. Contactez Beecom."
        return True, f"Licence valide — {dom} ({lic.get('licensee', 'Beecom')}, {lic.get('issued', '')})"
    except Exception as e:
        return False, f"licence.json illisible : {e}"
LICENCE_OK, LICENCE_MSG = licence_status()
# empreinte du site (détectable dans le code source des pages publiées — ne pas retirer)
import hashlib as _hhl
BCM_ID = _hhl.sha256(("bcm-moteur-beecom|" + re.sub(r"^https?://", "", CONFIG.get("SITE_URL", "")).split("/")[0].lower()).encode()).hexdigest()[:12]

ENV = os.environ.get("VFG_ENV") or CONFIG.get("ENV", "prod")
IS_PREPROD = ENV == "preprod"
SITE_URL = (CONFIG["PREPROD_URL"] if IS_PREPROD else CONFIG["SITE_URL"]).rstrip("/"); SITE_NAME = CONFIG["SITE_NAME"]; TAGLINE = CONFIG["TAGLINE"]
WEB3FORMS_KEY = CONFIG["WEB3FORMS_KEY"]; CALENDLY_URL = CONFIG["CALENDLY_URL"]; EMAIL = CONFIG["EMAIL"]
TEL_MOBILE = CONFIG["TEL"]; TEL_MOBILE_HREF = CONFIG["TEL_HREF"]; TEL_HOTLINE = CONFIG["TEL"]; TEL_HOTLINE_HREF = CONFIG["TEL_HREF"]
FORM_MODE = CONFIG.get("FORM_MODE", "php")
FORM_ACTION = "/api/contact.php" if FORM_MODE == "php" else "https://api.web3forms.com/submit"
LANGS = [tuple(x.split(":", 1)) if ":" in x else (x, x) for x in CONFIG.get("LANGS", "").split(",") if x.strip()]
DEFAULT_LANG = CONFIG.get("DEFAULT_LANG", "fr") or "fr"
ADDRESS = CONFIG["ADDRESS"]; AGENCY_URL = CONFIG["AGENCY_URL"]; GA_ID = CONFIG["GA_ID"]; DEFAULT_OG = CONFIG["DEFAULT_OG"]
MATOMO_URL = CONFIG["MATOMO_URL"].rstrip("/") + "/" if CONFIG["MATOMO_URL"] else ""; MATOMO_SITE_ID = str(CONFIG["MATOMO_SITE_ID"])
TODAY = datetime.date.today().isoformat()
REDIRECTS_PATH = os.path.join(ROOT, "redirects.json")   # [{"from": "/ancienne-url/", "to": "/nouvelle-url/"}]

METIERS = [
    ("campings", "Campings & hôtellerie de plein air", "tent"),
    ("restaurants", "Restaurants", "utensils"),
    ("artisans", "Artisans du bâtiment", "wrench"),
    ("hotels-chambres-d-hotes", "Hôtels & chambres d'hôtes", "bell"),
    ("coiffeurs-beaute", "Coiffeurs & beauté", "scissors"),
    ("commerces", "Commerces de proximité", "bag"),
    ("garages-automobile", "Garages & services auto", "car"),
    ("sante-bien-etre", "Santé & bien-être", "stethoscope"),
]
OFFRE = [
    ("/offre/", "Vue d'ensemble", "Comment ça marche, en 4 étapes"),
    ("/offre/installation-fiche-google/", "Installation & optimisation", "One-shot 390 € HT · plaque QR offerte"),
    ("/offre/forfaits-animation-fiche-google/", "Forfaits mensuels", "Starter · Booster · Turbo, dès 119 € HT/mois"),
    ("/offre/photos-videos-fiche-google/", "Photos & vidéos", "Shooting pro, drone FPV, reels"),
    ("/offre/avis-google/", "Avis Google", "Plaque QR, widget, réponses aux avis"),
]
_THEMES_DEFAULT = [
    ("visibilite-google-maps", "Visibilité & Google Maps"),
    ("optimiser-sa-fiche-google", "Optimiser sa fiche"),
    ("avis-google", "Avis Google"),
    ("agence-tarifs", "Agence & tarifs"),
]
def load_themes():
    """Catégories d'articles : blocks/_themes.json (gérées dans le back-office). Sans ce fichier,
    les défauts historiques ne s'appliquent qu'aux sites qui ont déjà leurs articles sous pages/guide/ ;
    un site importé sans blog démarre sans catégorie (elles se créent dans l'onglet Articles)."""
    fallback = _THEMES_DEFAULT if os.path.isdir(os.path.join(SRC, "guide")) else []
    try:
        t = json.load(open(os.path.join(ROOT, "blocks", "_themes.json"), encoding="utf-8"))
        return [(x["slug"], x["label"]) for x in t.get("themes", []) if x.get("slug")] or fallback
    except Exception:
        return fallback
GUIDE_THEMES = load_themes()
def _blog_base():
    """Préfixe des adresses du blog. Réglage BLOG_BASE (onglet SEO) :
    vide = catégories à la racine (/categorie/article/) sur les nouveaux sites ;
    rétro-compatibilité : si des articles vivent déjà sous pages/guide/, le préfixe reste guide."""
    b = (CONFIG.get("BLOG_BASE") or "").strip().strip("/")
    if b: return "" if b in (".", "racine", "root") else b
    return "guide" if os.path.isdir(os.path.join(SRC, "guide")) else ""
BLOG_BASE = _blog_base()
BLOG_PREFIX = (BLOG_BASE + "/") if BLOG_BASE else ""

# ------------------------------------------------------------------ HELPERS
def parse(path):
    raw = open(path, encoding="utf-8").read()
    m = re.match(r"^---\s*\n(.*?)\n---\s*\n(.*)$", raw, re.S)
    meta, body = {}, raw
    if m:
        for line in m.group(1).splitlines():
            if ":" in line and not line.startswith(" "):
                k, v = line.split(":", 1); meta[k.strip()] = v.strip()
        body = m.group(2)
    return meta, body

def url_from_path(rel):
    rel = rel.replace(os.sep, "/")
    if rel == "index.html": return "/"
    return "/" + rel[:-5] + "/" if rel.endswith(".html") else "/" + rel

def esc(s): return html.escape(s or "", quote=True)


# ---------- Bibliothèque de pictos (traits, 24x24) : utilisée par le menu Métiers et les blocs configurables ----------
ICONS = {
    "tent": ('Tente (camping)', '<path d="M3.5 21 12 4l8.5 17"/><path d="M12 4v17"/><path d="M8.5 21 12 14l3.5 7"/><path d="M2 21h20"/>'),
    "utensils": ('Couverts (restaurant)', '<path d="M3 2v7c0 1.1.9 2 2 2h4a2 2 0 0 0 2-2V2"/><path d="M7 2v20"/><path d="M21 15V2a5 5 0 0 0-5 5v6c0 1.1.9 2 2 2h3Zm0 0v7"/>'),
    "wrench": ('Clé (artisan)', '<path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/>'),
    "bell": ('Cloche (hôtel)', '<path d="M4 17h16"/><path d="M5 17a7 7 0 0 1 14 0"/><path d="M12 10V8"/><path d="M10 8h4"/><path d="M3 21h18"/>'),
    "scissors": ('Ciseaux (coiffure)', '<circle cx="6" cy="6" r="3"/><circle cx="6" cy="18" r="3"/><path d="M20 4 8.1 15.9"/><path d="M14.5 14.5 20 20"/><path d="M8.1 8.1 12 12"/>'),
    "bag": ('Sac (commerce)', '<path d="M6 7h12l1 14H5z"/><path d="M9 7V6a3 3 0 0 1 6 0v1"/><path d="M9 11v1a3 3 0 0 0 6 0v-1"/>'),
    "car": ('Voiture (garage)', '<path d="M19 17h2c.6 0 1-.4 1-1v-3c0-.9-.7-1.7-1.5-1.9C18.7 10.6 16 10 16 10s-1.3-1.4-2.2-2.3c-.5-.4-1.1-.7-1.8-.7H5c-.6 0-1.1.4-1.4.9l-1.4 2.9A3.7 3.7 0 0 0 2 12v4c0 .6.4 1 1 1h2"/><circle cx="7" cy="17" r="2"/><path d="M9 17h6"/><circle cx="17" cy="17" r="2"/>'),
    "stethoscope": ('Stéthoscope (santé)', '<path d="M4.8 2.3A.3.3 0 1 0 5 2H4a2 2 0 0 0-2 2v5a6 6 0 0 0 6 6 6 6 0 0 0 6-6V4a2 2 0 0 0-2-2h-1a.2.2 0 1 0 .3.3"/><path d="M8 15v1a6 6 0 0 0 6 6 6 6 0 0 0 6-6v-4"/><circle cx="20" cy="10" r="2"/>'),
    "search": ('Loupe', '<circle cx="11" cy="11" r="7"/><line x1="21" y1="21" x2="16.65" y2="16.65"/>'),
    "chart": ('Graphique barres', '<path d="M12 20V10"/><path d="M18 20V4"/><path d="M6 20v-4"/>'),
    "trend": ('Courbe en hausse', '<polyline points="23 6 13.5 15.5 8.5 10.5 1 18"/><polyline points="17 6 23 6 23 12"/>'),
    "check": ('Coche', '<polyline points="20 6 9 17 4 12"/>'),
    "warning": ('Attention', '<path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/>'),
    "user": ('Personne', '<path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/>'),
    "star": ('Étoile', '<polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/>'),
    "phone": ('Téléphone', '<path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72c.13.96.36 1.9.7 2.81a2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45c.91.34 1.85.57 2.81.7A2 2 0 0 1 22 16.92z"/>'),
    "map": ('Repère carte', '<path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"/><circle cx="12" cy="10" r="3"/>'),
    "calendar": ('Calendrier', '<rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/>'),
    "camera": ('Appareil photo', '<path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/>'),
    "shield": ('Bouclier', '<path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>'),
    "message": ('Bulle', '<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>'),
    "clock": ('Horloge', '<circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/>'),
    "euro": ('Euro', '<path d="M4 10h12"/><path d="M4 14h9"/><path d="M19 6a7.7 7.7 0 0 0-5.2-2A7.9 7.9 0 0 0 6 12c0 4.4 3.5 8 7.8 8 2 0 3.8-.8 5.2-2"/>'),
    "target": ('Cible', '<circle cx="12" cy="12" r="10"/><circle cx="12" cy="12" r="6"/><circle cx="12" cy="12" r="2"/>'),
    "heart": ('Cœur', '<path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/>'),
}
def icon_svg(key):
    key = (key or "").strip()
    if key not in ICONS: return ""
    return f'<svg viewBox="0 0 24 24" aria-hidden="true">{ICONS[key][1]}</svg>'

ICON_CHEV = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M6 9l6 6 6-6"/></svg>'


# ---------- Blocs « site » (menu, pied de page, pop-up) : blocks/_menu.json, blocks/_popup.json ----------
def site_blocks(name, lang=None):
    """Retourne {section: {champ: valeur | liste d'items}} depuis blocks/<name>.json (variante blocks/<name>.<lang>.json si elle existe)."""
    cands = []
    if lang and lang != DEFAULT_LANG: cands.append(os.path.join(ROOT, "blocks", f"{name}.{lang}.json"))
    cands.append(os.path.join(ROOT, "blocks", f"{name}.json"))
    for p in cands:
        if os.path.exists(p):
            d = json.load(open(p, encoding="utf-8")); out = {}
            for sec in d.get("sections", []):
                out[sec["id"]] = {f["key"]: (f.get("items", []) if f.get("type") == "repeat" else f.get("value", "")) for f in sec.get("fields", [])}
            return out
    return {}
def _lines(v):
    return [[c.strip() for c in l.split("|")] for l in str(v or "").splitlines() if l.strip()]
def _on(v): return str(v or "").strip().lower() in ("true", "1", "oui", "yes", "on")

SOCIAL_ICONS = {
    "SOCIAL_FACEBOOK": ("Facebook", '<path d="M18 2h-3a5 5 0 0 0-5 5v3H7v4h3v8h4v-8h3l1-4h-4V7a1 1 0 0 1 1-1h3z"/>'),
    "SOCIAL_INSTAGRAM": ("Instagram", '<rect x="2" y="2" width="20" height="20" rx="5" ry="5"/><path d="M16 11.37A4 4 0 1 1 12.63 8 4 4 0 0 1 16 11.37z"/><line x1="17.5" y1="6.5" x2="17.51" y2="6.5"/>'),
    "SOCIAL_LINKEDIN": ("LinkedIn", '<path d="M16 8a6 6 0 0 1 6 6v7h-4v-7a2 2 0 0 0-2-2 2 2 0 0 0-2 2v7h-4v-7a6 6 0 0 1 6-6z"/><rect x="2" y="9" width="4" height="12"/><circle cx="4" cy="4" r="2"/>'),
    "SOCIAL_YOUTUBE": ("YouTube", '<path d="M22.54 6.42a2.78 2.78 0 0 0-1.94-2C18.88 4 12 4 12 4s-6.88 0-8.6.46a2.78 2.78 0 0 0-1.94 2A29 29 0 0 0 1 11.75a29 29 0 0 0 .46 5.33A2.78 2.78 0 0 0 3.4 19c1.72.46 8.6.46 8.6.46s6.88 0 8.6-.46a2.78 2.78 0 0 0 1.94-2 29 29 0 0 0 .46-5.25 29 29 0 0 0-.46-5.33z"/><polygon points="9.75 15.02 15.5 11.75 9.75 8.48 9.75 15.02"/>'),
    "SOCIAL_TIKTOK": ("TikTok", '<path d="M9 12a4 4 0 1 0 4 4V4a5 5 0 0 0 5 5"/>'),
    "SOCIAL_X": ("X (Twitter)", '<path d="M4 4l16 16"/><path d="M20 4L4 20"/>'),
}
def social_html(cls="social"):
    items = []
    for k, (label, path) in SOCIAL_ICONS.items():
        u = (CONFIG.get(k) or "").strip()
        if u: items.append(f'<a href="{esc(u)}" target="_blank" rel="noopener" aria-label="{label}" title="{label}"><svg viewBox="0 0 24 24" aria-hidden="true">{path}</svg></a>')
    return f'<div class="{cls}">{"".join(items)}</div>' if items else ""

TRANS_URLS = {}   # rempli au build : {lang: {url_fr: url_traduite}} (slugs traduits, ex. "/metiers/campings/" → "/en/sectors/campsites/")

def lang_switcher(meta, url):
    """Sélecteur de langue automatique : n'affiche que les langues où CETTE page existe."""
    if not LANGS: return ""
    cur = meta.get("lang", DEFAULT_LANG)
    fru = meta.get("_fr_url", url)
    opts = []
    for code, label in LANGS:
        code = code.strip(); label = label.strip()
        if code == DEFAULT_LANG: href = fru
        elif fru in TRANS_URLS.get(code, {}): href = TRANS_URLS[code][fru]
        else: continue
        opts.append(f'<a href="{href}" lang="{code}" hreflang="{code}" class="{"on" if code == cur else ""}" title="{esc(label)}">{esc(code.upper())} <small>{esc(label)}</small></a>')
    if len(opts) < 2: return ""
    return f'<li class="lang has-dd"><button type="button" aria-expanded="false" aria-haspopup="true">{esc(cur.upper())} {ICON_CHEV}</button><div class="dropdown lang-dd">{"".join(opts)}</div></li>'

VFG_LANG_CSS = ("<style id=\"vfg-lang-css\">"
".vfg-lang{position:relative;list-style:none;display:inline-flex;align-items:center}"
".vfg-lang details{position:relative;margin:0}"
".vfg-lang summary{cursor:pointer;list-style:none;display:inline-flex;align-items:center;gap:.35em;font-weight:600;font-size:.88rem;padding:.35rem .6rem;border-radius:100px;border:1px solid rgba(128,138,157,.35)}"
".vfg-lang summary::-webkit-details-marker{display:none}"
".vfg-lang summary::after{content:\"\\25BE\";font-size:.7em;opacity:.6}"
".vfg-lang .vfg-lang-dd{position:absolute;right:0;top:100%;margin-top:8px;background:#fff;color:#1c2a38;border-radius:12px;box-shadow:0 14px 34px rgba(0,10,30,.18);padding:.45rem;display:flex;flex-direction:column;gap:.15rem;min-width:160px;z-index:400}"
".vfg-lang .vfg-lang-dd a{padding:.4rem .65rem;border-radius:8px;white-space:nowrap;text-decoration:none;color:inherit;font-size:.88rem;display:flex;gap:.5rem;align-items:baseline}"
".vfg-lang .vfg-lang-dd a small{opacity:.65;font-weight:400}"
".vfg-lang .vfg-lang-dd a:hover{background:#eef2f8}.vfg-lang .vfg-lang-dd a.on{font-weight:700}"
"</style>")

def lang_switcher_standalone(meta, url):
    """Sites importés (layout/) : sélecteur de langue autonome, injecté automatiquement dans l'en-tête
    dès qu'au moins une traduction de la page existe. Désactivable : LANG_SWITCH = "false" (Réglages)."""
    if not LANGS or (CONFIG.get("LANG_SWITCH", "true") or "true").lower() == "false": return ""
    cur = meta.get("lang", DEFAULT_LANG)
    fru = meta.get("_fr_url", url)
    opts = []
    for code, label in LANGS:
        code = code.strip(); label = label.strip()
        if code == DEFAULT_LANG: href = fru
        elif fru in TRANS_URLS.get(code, {}): href = TRANS_URLS[code][fru]
        else: continue
        opts.append(f'<a href="{href}" lang="{code}" hreflang="{code}" class="{"on" if code == cur else ""}">{esc(code.upper())} <small>{esc(label)}</small></a>')
    if len(opts) < 2: return ""
    return (f'<div class="vfg-lang"><details><summary aria-label="Choisir la langue">{esc(cur.upper())}</summary>'
            f'<div class="vfg-lang-dd">{"".join(opts)}</div></details></div>')

def nav_html(meta=None, url="/", lang=None):
    m = site_blocks("_menu", lang); nav = m.get("nav", {}); hd = m.get("header", {})
    lis = []
    for it in nav.get("items", []):
        label = esc(it.get("label", "")); href = (it.get("url") or "").strip()
        children = _lines(it.get("children"))
        if href and not children:
            lis.append(f'<li><a href="{esc(href)}">{label}</a></li>'); continue
        links = []
        if (it.get("head_label") or "").strip():
            small = f'<small>{esc(it.get("head_small",""))}</small>' if (it.get("head_small") or "").strip() else ""
            links.append(f'<a href="{esc(it.get("head_url") or "#")}"><b>{esc(it["head_label"])}</b>{small}</a>')
        for c in children:
            t = c[0] if len(c) > 0 else ""; u = c[1] if len(c) > 1 else "#"; d = c[2] if len(c) > 2 else ""; ic = c[3] if len(c) > 3 else ""
            if ic and icon_svg(ic): links.append(f'<a class="with-ico" href="{esc(u)}"><span class="mico">{icon_svg(ic)}</span>{esc(t)}</a>')
            else: links.append(f'<a href="{esc(u)}">{esc(t)}{f"<small>{esc(d)}</small>" if d else ""}</a>')
        wide = " wide" if _on(it.get("wide")) else ""
        lis.append(f'<li class="has-dd"><button type="button" aria-expanded="false" aria-haspopup="true">{label} {ICON_CHEV}</button><div class="dropdown{wide}">{"".join(links)}</div></li>')
    lang_li = lang_switcher(meta or {}, url) if _on(hd.get("show_lang", "true")) else ""
    cal = f'<a class="btn btn-outline mt-1" href="{CALENDLY_URL}" target="_blank" rel="noopener" data-calendly>{esc(hd.get("mobile_calendly_label"))}</a>' if (hd.get("mobile_calendly_label") or "").strip() else ""
    return ('\n<ul class="nav" id="nav">\n  ' + "".join(lis) + "\n  " + lang_li +
            f'\n  <li class="mobile-cta"><a class="btn btn-primary" href="{esc(hd.get("mobile_cta_url") or "/audit-gratuit/")}">{esc(hd.get("mobile_cta_label") or "Audit gratuit de ma fiche")}</a>'
            f'\n      {cal}\n      <p class="mt-1"><a href="mailto:{EMAIL}">{EMAIL}</a></p></li>\n</ul>')

def header_html(meta=None, url="/", lang=None):
    hd = site_blocks("_menu", lang).get("header", {})
    logo = hd.get("logo") or "/assets/img/logo-vfg.png"
    phone = f'<a class="btn btn-outline" href="tel:{TEL_MOBILE_HREF}">Appeler</a>' if _on(hd.get("mobile_phone", "true")) else ""
    return (f'\n<header class="site-header">\n  <div class="container header-inner">\n'
            f'    <a class="brand" href="/" aria-label="{esc(hd.get("logo_alt") or SITE_NAME)} — accueil"><img src="{esc(logo)}" alt="{esc(hd.get("logo_alt") or SITE_NAME)}" width="150" height="40"></a>\n'
            f'    {nav_html(meta, url, lang)}\n'
            f'    <div class="header-cta">\n      <a class="btn btn-primary btn-sm" href="{esc(hd.get("cta_url") or "/audit-gratuit/")}">{esc(hd.get("cta_label") or "Audit gratuit")}</a>\n    </div>\n'
            f'    <button class="burger" aria-label="Menu" aria-expanded="false" aria-controls="nav"><span></span><span></span><span></span></button>\n  </div>\n</header>\n'
            f'<div class="mobile-sticky">\n  <a class="btn btn-primary" href="{esc(hd.get("mobile_cta_url") or "/audit-gratuit/")}">{esc(hd.get("cta_label") or "Audit gratuit")}</a>\n  {phone}\n</div>')

def footer_html(lang=None):
    ft = site_blocks("_menu", lang).get("footer", {})
    cols = ""
    for c in ft.get("columns", []):
        lis = "".join(f'<li><a href="{esc(l[1] if len(l)>1 else "#")}"{" target=_blank rel=noopener" if len(l)>1 and l[1].startswith("http") else ""}>{esc(l[0])}</a></li>' for l in _lines(c.get("links")))
        cols += f'<div class="footer-col"><h4>{esc(c.get("title",""))}</h4><ul>{lis}</ul></div>'
    agency = f'<div class="by"><span>{esc(ft.get("agency_label") or "Un service de l’agence")}</span><a href="{AGENCY_URL}" target="_blank" rel="noopener"><img src="/assets/img/beecom-logo.png" alt="Beecom’ — agence digitale"></a></div>' if _on(ft.get("show_agency", "true")) else ""
    contact = f'<p class="mt-1" style="font-size:.85rem">{ADDRESS}<br><a href="tel:{TEL_MOBILE_HREF}">{TEL_MOBILE}</a>{" — " + esc(ft.get("phone_note")) if (ft.get("phone_note") or "").strip() else ""}<br><a href="mailto:{EMAIL}">{EMAIL}</a></p>' if _on(ft.get("show_contact", "true")) else ""
    social = social_html("social") if _on(ft.get("show_social", "true")) else ""
    legal = "".join(f'<a href="{esc(l[1] if len(l)>1 else "#")}">{esc(l[0])}</a>' for l in _lines(ft.get("legal")))
    copy = (ft.get("copyright") or "© {year} Beecom’ — votre-fiche-google.fr").replace("{year}", str(datetime.date.today().year))
    logo = ft.get("logo") or "/assets/img/logo-vfg-white.png"
    text = ft.get("text") or f"{TAGLINE}"
    ncols = max(1, len(ft.get("columns", [])))
    return (f'\n<footer class="site-footer">\n  <div class="container">\n    <div class="footer-top" style="--fcols:{ncols}">\n'
            f'      <div class="footer-brand">\n        <img src="{esc(logo)}" alt="{SITE_NAME}" width="210" height="26">\n        <p>{esc(text)}</p>\n        {agency}\n        {contact}\n        {social}\n      </div>\n'
            f'      {cols}\n    </div>\n    <div class="footer-bottom">\n      <div>{copy}</div>\n      <div class="legal">{legal}</div>\n    </div>\n  </div>\n</footer>')

def popup_html():
    pu = site_blocks("_popup").get("popup", {})
    if not _on(pu.get("enabled")): return ""
    img = f'<div class="popup-img"><img src="{esc(pu["image"])}" alt="" loading="lazy"></div>' if (pu.get("image") or "").strip() else ""
    title = f'<h3>{pu.get("title")}</h3>' if (pu.get("title") or "").strip() else ""
    sub = f'<p class="popup-sub">{pu.get("subtitle")}</p>' if (pu.get("subtitle") or "").strip() else ""
    text = f'<p>{render_field_value({"type":"textarea"}, pu.get("text"))}</p>' if (pu.get("text") or "").strip() else ""
    btn = f'<a class="btn btn-primary" href="{esc(pu.get("btn_url") or "#")}">{esc(pu["btn_label"])}</a>' if (pu.get("btn_label") or "").strip() else ""
    trig = {"section": "section", "délai": "delay", "immédiat": "now"}.get(pu.get("trigger", "section"), "section")
    freq = {"une fois par visite": "session", "une fois par jour": "day", "à chaque page": "always"}.get(pu.get("frequency", ""), "session")
    return (f'<div class="popup-backdrop" id="popup" hidden data-popup data-trigger="{trig}" data-section="{esc(pu.get("section_n") or "3")}" data-delay="{esc(pu.get("delay") or "8")}" data-freq="{freq}" role="dialog" aria-modal="true" aria-label="{esc(pu.get("title") or "Information")}">'
            f'<div class="popup{" has-img" if img else ""}"><button type="button" class="popup-close" data-popup-close aria-label="Fermer"><span class="x">&times;</span><span class="lbl">{esc(pu.get("close_label") or "fermer")}</span></button>'
            f'{img}<div class="popup-body">{title}{sub}{text}{btn}</div></div></div>')
def popup_pages_all():
    return (site_blocks("_popup").get("popup", {}).get("pages") or "accueil") != "accueil"

def bc_label_from(meta):
    """Intitulé d'une page dans un fil d'Ariane : bc_label, sinon titre court, sinon title raccourci."""
    v = (meta.get("bc_label") or "").strip() or (meta.get("card_title") or "").strip()
    if v: return v
    bc = (meta.get("breadcrumb") or "").strip()   # page encore à l'ancien format : son propre intitulé y est déjà choisi
    if bc:
        last = bc.split(";")[-1].strip()
        v = (last.split("|")[0] if "|" in last else last).strip()
        if v: return v
    t = (meta.get("title") or "").split("|")[0].strip()
    for sep in (" : ", " — ", " – "):
        if sep in t: t = t.split(sep)[0].strip(); break
    return t

_BC_LABELS = {}
def _page_label_for(url):
    """Intitulé de la page qui répond à cette URL (/offre/ → pages/offre.html ou offre/index.html)."""
    if url in _BC_LABELS: return _BC_LABELS[url]
    lab = None
    base = url.strip("/")
    for rel in (base + ".html", base + "/index.html"):
        p = os.path.join(SRC, rel)
        if os.path.exists(p):
            try: lab = bc_label_from(parse(p)[0])
            except Exception: lab = None
            break
    if not lab: lab = dict(GUIDE_THEMES).get(base.split("/")[-1])
    _BC_LABELS[url] = lab
    return lab

def auto_breadcrumb(url, meta):
    """Fil d'Ariane déduit de la parenté de l'URL : Accueil / parents existants / page.
    Les niveaux se calculent tout seuls ; seul l'intitulé (bc_label) se choisit page par page."""
    segs = [x for x in url.strip("/").split("/") if x]
    if not segs or url.endswith(".html"): return ""
    if LANGS and segs[0] in {c for c, _ in LANGS if c != DEFAULT_LANG}: return ""   # pages traduites : géré via les traductions
    items = [("Accueil", "/")]; acc = ""
    for sgm in segs[:-1]:
        acc += "/" + sgm
        lab = _page_label_for(acc + "/")
        if lab: items.append((lab, acc + "/"))
    items.append((bc_label_from(meta) or segs[-1].replace("-", " ").capitalize(), None))
    return ";".join(f"{n}|{u}" if u else n for n, u in items)

def breadcrumb_html(bc):
    """bc: 'Accueil|/;Métiers|/metiers/;Campings' """
    if not bc: return "", None
    items = []
    for part in bc.split(";"):
        part = part.strip()
        if "|" in part:
            name, url = part.split("|", 1); items.append((name.strip(), url.strip()))
        else: items.append((part, None))
    lis = []
    for name, url in items:
        lis.append(f'<li><a href="{url}">{esc(name)}</a></li>' if url else f'<li aria-current="page">{esc(name)}</li>')
    ld = {"@context": "https://schema.org", "@type": "BreadcrumbList", "itemListElement": [
        {"@type": "ListItem", "position": i + 1, "name": n, **({"item": SITE_URL + u} if u else {})} for i, (n, u) in enumerate(items)]}
    return f'<nav class="breadcrumb" aria-label="Fil d\'Ariane"><ol>{"".join(lis)}</ol></nav>', ld

def _org_addr():
    a = {"@type": "PostalAddress"}
    if CONFIG.get("ORG_STREET"): a["streetAddress"] = CONFIG["ORG_STREET"]
    if CONFIG.get("ORG_CITY"): a["addressLocality"] = CONFIG["ORG_CITY"]
    if CONFIG.get("ORG_POSTAL"): a["postalCode"] = CONFIG["ORG_POSTAL"]
    if CONFIG.get("ORG_REGION"): a["addressRegion"] = CONFIG["ORG_REGION"]
    a["addressCountry"] = CONFIG.get("ORG_COUNTRY") or "FR"
    if len(a) == 2 and not CONFIG.get("ORG_CITY"):   # rien de renseigné : défauts historiques vfg
        a.update({"addressLocality": "Saint-Jean-d'Illac", "postalCode": "33127", "addressRegion": "Nouvelle-Aquitaine"})
    return a
_ORG_TEL = CONFIG.get("ORG_TEL") or "+33662226303"
ORG_LD = {
    "@context": "https://schema.org", "@type": "Organization", "@id": SITE_URL + "/#org",
    "name": CONFIG.get("ORG_NAME") or (SITE_NAME + " — un service de l'agence Beecom'"), "url": SITE_URL,
    "logo": SITE_URL + (CONFIG.get("ORG_LOGO") or "/assets/img/logo-vfg.png"), "email": EMAIL, "telephone": _ORG_TEL,
    "parentOrganization": {"@type": "Organization", "name": "Beecom' — agence digitale", "url": AGENCY_URL},
    "address": _org_addr(),
    "areaServed": "FR",
    "contactPoint": [{"@type": "ContactPoint", "telephone": _ORG_TEL, "contactType": "sales", "availableLanguage": "fr"}],
}
SERVICE_LD = {
    "@context": "https://schema.org", "@type": "Service", "name": "Optimisation et animation de fiche d'établissement Google",
    "provider": {"@id": SITE_URL + "/#org"}, "areaServed": "FR", "serviceType": "Référencement local — Google Business Profile",
    "offers": [
        {"@type": "Offer", "name": "Installation & optimisation complète", "price": "390", "priceCurrency": "EUR", "url": SITE_URL + "/offre/installation-fiche-google/"},
        {"@type": "Offer", "name": "Forfait Starter", "price": "119", "priceCurrency": "EUR", "url": SITE_URL + "/offre/forfaits-animation-fiche-google/"},
        {"@type": "Offer", "name": "Forfait Booster", "price": "149", "priceCurrency": "EUR", "url": SITE_URL + "/offre/forfaits-animation-fiche-google/"},
        {"@type": "Offer", "name": "Forfait Turbo", "price": "219", "priceCurrency": "EUR", "url": SITE_URL + "/offre/forfaits-animation-fiche-google/"},
    ],
}

def faq_ld(body):
    """Extrait automatiquement les <details><summary>Q</summary><div class=answer>R</div></details> en FAQPage."""
    qs = re.findall(r"<details[^>]*>\s*<summary>(.*?)</summary>\s*<div class=\"answer\">(.*?)</div>\s*</details>", body, re.S)
    if not qs: return None
    strip = lambda s: re.sub(r"\s+", " ", re.sub(r"<[^>]+>", "", s)).strip()
    return {"@context": "https://schema.org", "@type": "FAQPage", "mainEntity": [
        {"@type": "Question", "name": strip(q), "acceptedAnswer": {"@type": "Answer", "text": strip(a)}} for q, a in qs]}

def reading_time(body):
    words = len(re.sub(r"<[^>]+>", " ", body).split())
    return max(1, round(words / 220))


# ------------------------------------------------------------------ ARTICLES (listes automatiques)
THEME_LABEL = dict(GUIDE_THEMES)
ARTICLES = []   # rempli par index_articles()
CURRENT_URL = ""

def index_articles():
    ARTICLES.clear()
    bdir = os.path.join(SRC, BLOG_BASE) if BLOG_BASE else SRC
    themes = {sl for sl, _ in GUIDE_THEMES}
    if BLOG_BASE and os.path.isdir(bdir):   # tolère un dossier de thème absent de _themes.json (historique)
        themes |= {d for d in os.listdir(bdir) if os.path.isdir(os.path.join(bdir, d))}
    for theme in sorted(themes):
        tdir = os.path.join(bdir, theme)
        if not os.path.isdir(tdir): continue
        for fn in os.listdir(tdir):
            if not fn.endswith(".html"): continue
            meta, body = parse(os.path.join(tdir, fn))
            if meta.get("type") != "article" or meta.get("draft", "false").lower() == "true": continue
            title = meta.get("card_title") or re.sub(r"\s*\|\s*" + re.escape(SITE_NAME) + r"\s*$", "", meta.get("title", ""))
            ARTICLES.append({
                "theme": theme, "theme_label": THEME_LABEL.get(theme, theme), "slug": fn[:-5],
                "url": f"/{BLOG_PREFIX}{theme}/{fn[:-5]}/", "title": title,
                "excerpt": meta.get("excerpt") or meta.get("description", ""),
                "image": meta.get("og_image") or DEFAULT_OG, "date": meta.get("date", TODAY),
                "reading": meta.get("reading") or reading_time(body),
            })
    ARTICLES.sort(key=lambda a: a["date"], reverse=True)

def article_card(a):
    return (f'<a class="card card-link card-img" href="{a["url"]}"><img src="{a["image"]}" alt="{esc(a["title"])}" loading="lazy">'
            f'<div class="card-body"><div class="card-meta"><span>{esc(a["theme_label"])}</span><span>{a["reading"]} min</span></div>'
            f'<h3>{esc(a["title"])}</h3><p>{esc(a["excerpt"])}</p><span class="more">Lire →</span></div></a>')

def expand_article_placeholders(body):
    def cards(m):
        theme, opt = m.group(1), (m.group(2) or "")
        sel = [a for a in ARTICLES if a["url"] != CURRENT_URL and (theme == "all" or a["theme"] == theme)]
        mfill = re.match(r"fill(\d+)", opt)
        if mfill:
            n = int(mfill.group(1))
            if len(sel) < n: sel = sel + [a for a in ARTICLES if a not in sel and a["url"] != CURRENT_URL][: n - len(sel)]
        mlat = re.match(r"latest(\d+)", opt) or (re.match(r"(\d+)", opt))
        if mlat and not mfill: sel = sel[: int(mlat.group(1))]
        return "".join(article_card(a) for a in sel)
    body = re.sub(r"\{\{ARTICLE_CARDS:([a-z0-9-]+)(?::([a-z0-9]+))?\}\}", cards, body)
    def links(m):
        sel = [a for a in ARTICLES if a["theme"] == m.group(1)]
        return "<ul>" + "".join(f'<li><a href="{a["url"]}">{esc(a["title"])}</a></li>' for a in sel) + "</ul>"
    body = re.sub(r"\{\{ARTICLE_LINKS:([a-z0-9-]+)\}\}", links, body)
    return body


# ---------- Blocs configurables (style ACF) : blocks/<page>.json + jetons {{B:section.champ}} dans la page ----------
BLOCKS_DIR = os.path.join(ROOT, "blocks")
LAYOUT_DIR = os.path.join(ROOT, "layout")
def asset_exists(rel):
    return os.path.exists(os.path.join(ROOT, rel.lstrip("/")))
def layout_file(name, lang=None):
    if lang and lang != DEFAULT_LANG:
        base, ext = os.path.splitext(name)
        fp = os.path.join(LAYOUT_DIR, f"{base}.{lang}{ext}")
        if os.path.exists(fp): return open(fp, encoding="utf-8").read()
    fp = os.path.join(LAYOUT_DIR, name)
    return open(fp, encoding="utf-8").read() if os.path.exists(fp) else None
def blocks_key(rel):
    return re.sub(r"\.html$", "", rel).replace("/", "__")
def blocks_path(rel):
    return os.path.join(BLOCKS_DIR, blocks_key(rel) + ".json")
def load_blocks(rel):
    p = blocks_path(rel)
    if not os.path.exists(p): return None
    return json.load(open(p, encoding="utf-8"))
def _truthy(v):
    return str(v or "").strip().lower() not in ("", "false", "0", "non", "no", "off")
def render_field_value(f, v):
    t = f.get("type", "text")
    v = "" if v is None else str(v)
    if t == "icon": return icon_svg(v)
    if t == "bool": return "true" if _truthy(v) else ""
    if t == "textarea":
        if re.search(r"<(p|ul|ol|li|br|div|h\d)\b", v): return v
        paras = [x.strip().replace("\n", "<br>") for x in re.split(r"\n\s*\n", v.strip()) if x.strip()]
        return "</p><p>".join(paras)
    return v
def _fill(tpl, ctx):
    def cond(m):
        k, op, txt = m.group(1), m.group(2), m.group(3)
        if k not in ctx: return m.group(0)
        ok = _truthy(ctx[k])
        return txt if (ok if op == "?" else not ok) else ""
    tpl = re.sub(r"\{(\w+)([?!])([^{}]*)\}", cond, tpl)
    return re.sub(r"\{(\w+)\}", lambda m: str(ctx[m.group(1)]) if m.group(1) in ctx else m.group(0), tpl)
def apply_blocks(body, rel, data=None):
    data = data if data is not None else load_blocks(rel)
    if not data: return body
    fields = {}
    for sec in data.get("sections", []):
        for f in sec.get("fields", []): fields[(sec["id"], f["key"])] = f
    def block(m):
        f = fields.get((m.group(1), m.group(2)))
        if not f: return ""
        tpl = m.group(3)
        out = []
        if f.get("type") == "repeat":
            for i, row in enumerate(f.get("items", [])):
                ctx = {sub["key"]: render_field_value(sub, row.get(sub["key"], "")) for sub in f.get("fields", [])}
                ctx["n"] = i + 1
                for sub in f.get("fields", []):
                    if sub.get("type") == "lines":
                        wrap = sub.get("wrap", "{line}")
                        ctx[sub["key"]] = "".join(_fill(wrap, {"line": l.strip()}) for l in str(row.get(sub["key"], "")).splitlines() if l.strip())
                out.append(_fill(tpl, ctx))
        elif f.get("type") == "lines":
            for l in str(f.get("value", "")).splitlines():
                if l.strip(): out.append(_fill(tpl, {"line": l.strip()}))
        elif f.get("type") == "bool":
            if _truthy(f.get("value", "")): out.append(tpl)
        return "".join(out)
    def scalar(m):
        f = fields.get((m.group(1), m.group(2)))
        if not f: return ""
        if f.get("type") in ("repeat", "lines", "bool"): return m.group(0)   # traités en bloc ci-dessous
        return render_field_value(f, f.get("value", ""))
    body = re.sub(r"\{\{B:([\w-]+)\.([\w-]+)\}\}", scalar, body)
    body = re.sub(r"\{\{B:([\w-]+)\.([\w-]+)\}\}(.*?)\{\{/B\}\}", block, body, flags=re.S)
    return re.sub(r"\{\{B:([\w-]+)\.([\w-]+)\}\}", "", body)

VFG_UTILS_CSS = ("<style id=\"vfg-utils\">"
".vfg-bg{background:var(--vfg-bg)!important}"
".vfg-rounded{border-radius:24px;overflow:hidden}"
".vfg-pad-compact{padding-top:26px!important;padding-bottom:26px!important}"
".vfg-pad-large{padding-top:110px!important;padding-bottom:110px!important}"
".vfg-full .container{max-width:none!important}"
".vfg-flip :where(.two-col,.hero-grid,[class*=grid],[class*=cols],[class*=row]:not(nav)){direction:rtl}"
".vfg-flip :where(.two-col,.hero-grid,[class*=grid],[class*=cols],[class*=row]:not(nav))>*{direction:ltr}"
".vfg-hd{display:block;font-weight:700;line-height:1.25;margin:0 0 .55em}"
".vfg-hd-1{font-size:2.2rem}.vfg-hd-2{font-size:1.8rem}.vfg-hd-3{font-size:1.35rem}.vfg-hd-4{font-size:1.15rem}.vfg-hd-5{font-size:1.05rem}.vfg-hd-6{font-size:.95rem}"
"</style>")

def render(meta, body, url):
    global CURRENT_URL; CURRENT_URL = url
    title = meta.get("title", SITE_NAME)
    desc = meta.get("description", "")
    canonical = meta.get("canonical", "").strip() or (SITE_URL + url)
    if canonical.startswith("/"): canonical = SITE_URL + canonical
    og_title = meta.get("og_title", "").strip() or title
    og_desc = meta.get("og_description", "").strip() or desc
    _og_rel = meta.get("og_image", DEFAULT_OG)
    og_img = (SITE_URL + _og_rel) if (asset_exists(_og_rel) or meta.get("og_image")) else ""
    noindex = meta.get("noindex", "false").lower() == "true" or IS_PREPROD
    # fil d'Ariane : intitulé choisi page par page (bc_label), niveaux déduits de la parenté de l'URL.
    # L'ancien format explicite (Accueil|/;…) reste honoré s'il est présent (pages historiques).
    _bc = meta.get("breadcrumb", "").strip()
    if not _bc and ("{{BREADCRUMB}}" in body or meta.get("bc_label")):   # jamais sur les pages importées telles quelles (parité octet)
        _bc = auto_breadcrumb(url, meta)
    bc_html, bc_ld = breadcrumb_html(_bc)
    body = expand_article_placeholders(body)
    body = body.replace("{{BREADCRUMB}}", bc_html)
    # variables globales
    body = (body.replace("{{CALENDLY}}", CALENDLY_URL).replace("{{EMAIL}}", EMAIL)
                .replace("{{TEL}}", TEL_MOBILE).replace("{{TEL_HREF}}", TEL_MOBILE_HREF)
                .replace("{{HOTLINE}}", TEL_HOTLINE).replace("{{HOTLINE_HREF}}", TEL_HOTLINE_HREF)
                .replace("{{W3F}}", WEB3FORMS_KEY).replace("{{READING}}", str(meta.get("reading") or reading_time(body)))
                .replace("{{DATE_FR}}", meta.get("date_fr", "")))
    lds = [] if os.path.isdir(LAYOUT_DIR) else [ORG_LD]
    if bc_ld: lds.append(bc_ld)
    if meta.get("schema") == "service": lds.append(SERVICE_LD)
    if meta.get("type") == "article":
        lds.append({"@context": "https://schema.org", "@type": "Article", "headline": title, "description": desc,
                    "image": og_img or None, "datePublished": meta.get("date", TODAY), "dateModified": meta.get("modified", meta.get("date", TODAY)),
                    "author": {"@type": "Organization", "name": "Beecom'", "url": AGENCY_URL},
                    "publisher": {"@id": SITE_URL + "/#org"}, "mainEntityOfPage": canonical, "inLanguage": "fr-FR"})
    if meta.get("type") == "local":
        lds.append({"@context": "https://schema.org", "@type": "LocalBusiness", "name": "Beecom' — agence fiche Google Bordeaux",
                    "image": SITE_URL + "/assets/img/equipe-beecom.webp", "url": canonical, "telephone": "+33662226303", "email": EMAIL,
                    "address": ORG_LD["address"], "priceRange": "€€", "areaServed": ["Bordeaux", "Gironde", "Nouvelle-Aquitaine", "France"],
                    "parentOrganization": {"@id": SITE_URL + "/#org"}})
    f = faq_ld(body)
    if f: lds.append(f)
    ld_html = "\n".join(f'<script type="application/ld+json">{json.dumps(l, ensure_ascii=False)}</script>' for l in lds)
    # site importé : les données structurées d'origine de la page sont conservées telles quelles (importer.py)
    if os.path.isdir(LAYOUT_DIR) and meta.get("ld_json"):
        ld_html = meta["ld_json"].replace("|||", "\n")
    ga = ""
    if GA_ID:
        ga = f'<script async src="https://www.googletagmanager.com/gtag/js?id={GA_ID}"></script><script>window.dataLayer=window.dataLayer||[];function gtag(){{dataLayer.push(arguments)}}gtag("js",new Date());gtag("config","{GA_ID}",{{anonymize_ip:true}});</script>'
    if MATOMO_URL and MATOMO_SITE_ID:
        ga += (f'<script>var _paq=window._paq=window._paq||[];_paq.push(["disableCookies"]);_paq.push(["trackPageView"]);_paq.push(["enableLinkTracking"]);'
               f'(function(){{var u="{MATOMO_URL}";_paq.push(["setTrackerUrl",u+"matomo.php"]);_paq.push(["setSiteId","{MATOMO_SITE_ID}"]);'
               f'var d=document,g=d.createElement("script"),s=d.getElementsByTagName("script")[0];g.async=true;g.src=u+"matomo.js";s.parentNode.insertBefore(g,s);}})();</script>')
    body_class = meta.get("body_class", "")
    lang = meta.get("lang", DEFAULT_LANG)
    hreflang = ""
    if LANGS:
        fru = meta.get("_fr_url", url)
        have = sorted(c for c in TRANS_URLS if fru in TRANS_URLS[c])
        if have:
            hreflang = f'<link rel="alternate" hreflang="{DEFAULT_LANG}" href="{SITE_URL}{fru}">'
            hreflang += "".join(f'<link rel="alternate" hreflang="{c}" href="{SITE_URL}{TRANS_URLS[c][fru]}">' for c in have)
            hreflang += f'<link rel="alternate" hreflang="x-default" href="{SITE_URL}{fru}">'
    head_extra = (CONFIG.get("CMP_SCRIPT") or "") + (CONFIG.get("HEAD_CODE") or "")
    if "vfg-" in body: head_extra += VFG_UTILS_CSS
    popup = popup_html() if (url == "/" or popup_pages_all()) else ""
    # --- site importé : layout/ remplace l'habillage par défaut (head/header/footer/scripts d'origine)
    # en-tête : variante optionnelle pour la page d'accueil (layout/header-home.html) — menu
    # d'accueil différent des pages intérieures. Absente = même en-tête partout.
    _is_home = url == "/" or bool(re.fullmatch(r"/[a-z]{2,3}/", url))
    _lh = layout_file("header-home.html", lang) if _is_home else None
    if _lh is None: _lh = layout_file("header.html", lang)
    _lf, _lhead, _lsc = layout_file("footer.html", lang), layout_file("head.html", lang), layout_file("scripts.html", lang)
    head_links = _lhead if _lhead is not None else '''<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
<link rel="stylesheet" href="/assets/css/style.css">
<link rel="stylesheet" href="https://assets.calendly.com/assets/external/widget.css">'''
    header_block = ("\n" + _lh) if _lh is not None else header_html(meta, url, lang)
    if _lh is not None:
        # site importé : injection automatique du sélecteur de langue dans l'en-tête
        sw = lang_switcher_standalone(meta, url)
        if sw:
            head_extra += VFG_LANG_CSS
            if '<button class="burger"' in header_block:
                header_block = header_block.replace('<button class="burger"', sw + '<button class="burger"', 1)
            elif "</header>" in header_block:
                header_block = header_block.replace("</header>", sw + "</header>", 1)
    footer_block = _lf if _lf is not None else footer_html(lang)
    scripts_block = _lsc if _lsc is not None else '''<script src="/assets/js/main.js" defer></script>
<script src="https://assets.calendly.com/assets/external/widget.js" async></script>'''
    if "data-vfg-trk" in body:
        scripts_block += ("<script>document.addEventListener('click',function(e){var el=e.target.closest('[data-vfg-trk]');if(!el)return;"
                          "var id=el.getAttribute('data-vfg-trk');"
                          "try{if(window._paq)_paq.push(['trackEvent','CTA',id,location.pathname]);}catch(_){}"
                          "try{if(window.gtag)gtag('event','cta_click',{cta_id:id,page_path:location.pathname});}catch(_){}});</script>")
    if _lsc is not None and popup:
        scripts_block += '<link rel="stylesheet" href="/assets/vfg-popup.css"><script src="/assets/vfg-popup.js" defer></script>'
    body = body.replace("{{INSTA_FEED}}", CONFIG.get("INSTA_WIDGET") or "").replace("{{FORM_ACTION}}", FORM_ACTION).replace("{{SOCIAL}}", social_html("social social-inline"))
    tw_extra = (f'\n<meta name="twitter:title" content="{esc(og_title)}">\n<meta name="twitter:description" content="{esc(og_desc)}">'
                + (f'\n<meta name="twitter:image" content="{og_img}">' if og_img else ""))
    # si la page importée contient déjà son propre <main>, on ne double pas la balise
    main_block = body if re.search(r"<main\b", body, re.I) else f'<main id="main">\n{body}\n</main>'
    # habillage moteur (site non importé) : theme-color + icônes ajoutés ici ; site importé : déjà dans layout/head.html
    if _lhead is None:
        head_links = "\n".join(x for x in [
            '<meta name="theme-color" content="#000b22">',
            '<link rel="icon" href="/assets/img/favicon.svg" type="image/svg+xml">' if asset_exists('assets/img/favicon.svg') else '',
            '<link rel="apple-touch-icon" href="/assets/img/apple-touch-icon.png">' if asset_exists('assets/img/apple-touch-icon.png') else ''] if x) + "\n" + head_links
    _fav = (CONFIG.get("FAVICON") or "").strip()
    if _fav:
        head_links = re.sub(r'<link\b[^>]*rel="(?:shortcut )?icon"[^>]*>\s*', "", head_links)
        _fmime = {"svg": "image/svg+xml", "ico": "image/x-icon", "png": "image/png"}.get(_fav.rsplit(".", 1)[-1].lower(), "")
        head_links = f'<link rel="icon" href="{_fav}"' + (f' type="{_fmime}"' if _fmime else "") + ">\n" + head_links
    page = f'''<!DOCTYPE html>
<html lang="{lang}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="generator" content="Beecom Moteur HTML">
<!--bcm:{BCM_ID}-->
{head_extra}
<title>{html.escape(title, quote=False)}</title>
<meta name="description" content="{esc(desc)}">
<link rel="canonical" href="{canonical}">
{hreflang}
{'<meta name="robots" content="noindex,follow">' if noindex else '<meta name="robots" content="index,follow,max-image-preview:large">'}
<meta property="og:type" content="{'article' if meta.get('type')=='article' else 'website'}">
<meta property="og:site_name" content="{SITE_NAME}">
<meta property="og:locale" content="{ {"fr":"fr_FR","en":"en_GB","es":"es_ES","de":"de_DE","it":"it_IT","nl":"nl_NL","pt":"pt_PT"}.get(lang, lang) }">
<meta property="og:title" content="{esc(og_title)}">
<meta property="og:description" content="{esc(og_desc)}">
<meta property="og:url" content="{canonical}">
{f'<meta property="og:image" content="{og_img}">' if og_img else ''}
<meta name="twitter:card" content="summary_large_image">{tw_extra}
{head_links}
{ld_html}
{ga}
</head>
<body class="{body_class}" data-form-mode="{FORM_MODE}">
{header_block}
{main_block}
{footer_block}
{popup}
{scripts_block}
<!--bcm:{BCM_ID}:moteur-beecom-agence-beecom.fr-->
</body>
</html>'''
    if lang != DEFAULT_LANG and TRANS_URLS.get(lang):
        mp = TRANS_URLS[lang]
        # réécrit les liens internes vers leurs équivalents traduits — SAUF les liens du sélecteur
        # de langue (ils portent hreflang="…" et doivent garder leur cible d'origine, ex. retour au FR)
        page = re.sub(r'href="(/[^"#]*)"(?![^<>]*\bhreflang=)', lambda m: f'href="{mp[m.group(1)]}"' if m.group(1) in mp else m.group(0), page)
    page = alt_fallback(page)
    page = perf_optimize(page)
    if IS_PREPROD:
        # en préprod, toutes les URLs absolues du site (y compris encodées dans les liens de partage) pointent vers la préprod
        prod = CONFIG["SITE_URL"].rstrip("/")
        if prod and prod != SITE_URL:
            from urllib.parse import quote as _q
            page = page.replace(prod, SITE_URL).replace(_q(prod, safe=""), _q(SITE_URL, safe=""))
    return page


# ------------------------------------------------------------------ Optimisations de performance (PageSpeed)
# Appliquées à chaque génération (désactivables : PERF_OPTIMS = "false" dans les Réglages/config.json).
_VARIANT_WIDTHS = (480, 800)
ALT_FILLED = 0   # compteur d'alt de secours posés au dernier build

def _alt_from_name(src):
    """Alt de secours dérivé du nom de fichier : 'equipe-beecom-bordeaux.webp' → 'Equipe beecom bordeaux'."""
    n = os.path.splitext(os.path.basename(src.split("?")[0]))[0]
    n = re.sub(r"-\d{2,4}(x\d{2,4})?$", "", n)          # suffixes de taille (…-960, …-1200x661)
    n = re.sub(r"-[0-9a-f]{6}-\d{3,4}$", "", n)         # suffixes de variantes _v
    n = re.sub(r"[-_]+", " ", n).strip()
    return (n[:1].upper() + n[1:]) if len(n) > 2 else ""

def alt_fallback(page):
    """Aucune image publiée sans texte alternatif : alt manquant ou vide → alt dérivé du nom de fichier.
    (Le bouton « Générer les ALT manquants (IA) » du back-office écrit ensuite de vraies descriptions.)"""
    global ALT_FILLED
    def rep(m):
        global ALT_FILLED
        tag = m.group(0)
        has = re.search(r'\balt="([^"]*)"', tag)
        if has and has.group(1).strip(): return tag
        sm = re.search(r'\bsrc="([^"]+)"', tag)
        if not sm or sm.group(1).startswith("data:"): return tag
        alt = esc(_alt_from_name(sm.group(1)))
        if not alt: return tag
        ALT_FILLED += 1
        if has: return tag.replace(has.group(0), f'alt="{alt}"', 1)
        return tag.replace("<img", f'<img alt="{alt}"', 1)
    return re.sub(r"<img\b[^>]*>", rep, page)

def _img_variants(src_rel):
    """Pour /assets/img/x.webp (≥ 800 px de large), crée des variantes 480/800 px dans assets/img/_v/
    (réutilisées d'un build à l'autre, copiées dans dist/). Retourne [(url, largeur)] + original, ou []."""
    m = re.match(r"^/assets/(.+)\.(jpe?g|png|webp)$", src_rel, re.I)
    if not m: return []
    fp = os.path.join(ROOT, "assets", *m.group(1).split("/")) + "." + m.group(2)
    if not os.path.isfile(fp) or "/_v/" in src_rel: return []
    try:
        from PIL import Image
    except Exception:
        return []
    try:
        im = Image.open(fp); w0 = im.width
    except Exception:
        return []
    if w0 < 800: return []
    h6 = hashlib.sha1(src_rel.encode()).hexdigest()[:6]
    base = os.path.splitext(os.path.basename(fp))[0] + "-" + h6; ext = os.path.splitext(fp)[1]
    vdir_src = os.path.join(ROOT, "assets", "img", "_v"); os.makedirs(vdir_src, exist_ok=True)
    vdir_dist = os.path.join(DIST, "assets", "img", "_v"); os.makedirs(vdir_dist, exist_ok=True)
    out = []
    for w in _VARIANT_WIDTHS:
        if w >= w0: continue
        name = f"{base}-{w}{ext}"; vp = os.path.join(vdir_src, name)
        if not os.path.exists(vp) or os.path.getmtime(vp) < os.path.getmtime(fp):   # image remplacée → variante refaite
            try:
                im2 = im.copy(); im2.thumbnail((w, 100000))
                if ext.lower() in (".jpg", ".jpeg"): im2 = im2.convert("RGB"); im2.save(vp, quality=82, optimize=True)
                else: im2.save(vp, optimize=True)
            except Exception:
                continue
        try:
            shutil.copy2(vp, os.path.join(vdir_dist, name))
        except Exception: pass
        out.append((f"/assets/img/_v/{name}", w))
    return out + [(src_rel, w0)] if out else []

def perf_optimize(page):
    if (CONFIG.get("PERF_OPTIMS", "true") or "true").lower() == "false": return page
    # 1) Google Fonts : feuille de style non bloquante (preload + media=print → all)
    def font_css(m):
        tag = m.group(0)
        if 'media=' in tag or "stylesheet" not in tag: return tag
        href = re.search(r'href="([^"]+)"', tag)
        if not href: return tag
        u = href.group(1)
        return (f'<link rel="preload" as="style" href="{u}">'
                f'<link rel="stylesheet" href="{u}" media="print" onload="this.media=\'all\'">'
                f'<noscript><link rel="stylesheet" href="{u}"></noscript>')
    page = re.sub(r'<link\b[^>]*fonts\.googleapis\.com/css[^>]*>', font_css, page)
    # 2) Calendly : CSS non bloquante + script chargé après l'affichage de la page
    page = re.sub(r'<link\b[^>]*assets\.calendly\.com[^>]*widget\.css[^>]*>',
                  '<link rel="stylesheet" href="https://assets.calendly.com/assets/external/widget.css" media="print" onload="this.media=\'all\'">', page)
    page = re.sub(r'<script\b[^>]*assets\.calendly\.com[^>]*widget\.js[^>]*>\s*</script>',
                  '<script>(function(){function l(){if(window.__cly)return;window.__cly=1;var s=document.createElement("script");s.src="https://assets.calendly.com/assets/external/widget.js";s.async=true;document.head.appendChild(s)}'
                  'if(document.readyState==="complete")l();else addEventListener("load",l);addEventListener("pointerdown",l,{once:true,passive:true});addEventListener("touchstart",l,{once:true,passive:true})})();</script>', page)
    # 3) Scripts de consentement (Sirdata & co) : jamais bloquants
    page = re.sub(r'<script (?![^>]*(?:async|defer))(?=[^>]*src="https?://[^"]*(?:consentframework|sirdata|cookiebot|axeptio|tarteaucitron)[^"]*")',
                  '<script async ', page)
    # 4) Image principale (LCP) : priorité de chargement haute sur la première image eager
    def prio(m):
        tag = m.group(0)
        return tag if "fetchpriority" in tag else tag.replace("<img ", '<img fetchpriority="high" ', 1)
    page = re.sub(r'<img\b[^>]*loading="eager"[^>]*>', prio, page, count=1)
    # 5) Images larges : variantes redimensionnées + srcset (le mobile télécharge la bonne taille)
    def srcset(m):
        tag = m.group(0)
        if "srcset" in tag or "data-src" in tag: return tag
        sm = re.search(r'src="(/assets/[^"]+)"', tag)
        if not sm: return tag
        var = _img_variants(sm.group(1).split("?")[0])
        if not var: return tag
        ss = ", ".join(f"{u} {w}w" for u, w in var)
        return tag.replace("<img ", f'<img srcset="{ss}" ', 1)
    page = re.sub(r"<img\b[^>]*>", srcset, page)
    return page




CONTACT_PHP = r"""<?php
// Formulaires du site — généré par build.py (réglages du back-office).
// Envoie 2 e-mails HTML (multipart avec version texte) : notification à l'agence + accusé de réception au client.
header('Content-Type: application/json; charset=utf-8');
$cfg = json_decode('__CFG__', true);
if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); echo json_encode(['success'=>false,'message'=>'Méthode non autorisée']); exit; }
if (!empty($_POST['botcheck'])) { echo json_encode(['success'=>true]); exit; }
$skip = ['access_key','botcheck','from_name','subject','page','consent','redirect'];
$email = filter_var(trim($_POST['email'] ?? ''), FILTER_VALIDATE_EMAIL);
$nom = trim($_POST['nom'] ?? ''); if ($nom === '') $nom = trim($_POST['name'] ?? '');
$sujet = trim($_POST['subject'] ?? 'Demande'); $page = trim($_POST['page'] ?? '');
$labels = ['fiche'=>'Fiche Google','nom'=>'Nom','telephone'=>'Téléphone','tel'=>'Téléphone','email'=>'E-mail','secteur'=>'Secteur','message'=>'Message','etablissement'=>'Établissement','ville'=>'Ville','name'=>'Nom'];
$recap = ''; $rows = '';
foreach ($_POST as $k => $v) {
  if (in_array($k, $skip)) continue;
  $v = trim(is_array($v) ? implode(', ', $v) : (string)$v); if ($v === '') continue;
  $lab = $labels[$k] ?? ucfirst(str_replace('_',' ',$k)); $vs = strip_tags($v);
  $recap .= "$lab : $vs\n";
  $rows .= '<tr><td style="padding:9px 14px;border-bottom:1px solid #e6eaef;color:#7a8594;font-size:13px;white-space:nowrap;vertical-align:top">'.htmlspecialchars($lab).'</td><td style="padding:9px 14px;border-bottom:1px solid #e6eaef;color:#1c2a38;font-size:14px">'.nl2br(htmlspecialchars($vs)).'</td></tr>';
}
$recap .= 'Consentement : ' . (!empty($_POST['consent']) ? 'oui' : 'non') . "\n";
$vars = ['{nom}'=>$nom ?: '—', '{email}'=>$email ?: '—', '{sujet}'=>$sujet, '{page}'=>$page, '{recap}'=>$recap, '{date}'=>date('d/m/Y H:i'),
         '{fiche}'=>trim($_POST['fiche'] ?? ''), '{message}'=>trim($_POST['message'] ?? ''), '{telephone}'=>trim($_POST['telephone'] ?? '')];
$from = $cfg['FORM_FROM']; $fromName = $cfg['FORM_FROM_NAME']; $to = $cfg['FORM_TO'];
$site = rtrim($cfg['SITE_URL'] ?? '', '/'); $siteName = $cfg['SITE_NAME'] ?? $fromName;
$logo = $cfg['MAIL_LOGO'] ? '<img src="'.$site.$cfg['MAIL_LOGO'].'" alt="'.htmlspecialchars($siteName).'" width="190" style="display:block;max-width:190px;height:auto">' : '<span style="color:#ffffff;font-size:18px;font-weight:bold">'.htmlspecialchars($siteName).'</span>';
$enc = function ($s) { return '=?UTF-8?B?' . base64_encode($s) . '?='; };
function gab($logo, $title, $intro, $table, $foot, $btn, $siteName) {
  return '<!DOCTYPE html><html><body style="margin:0;padding:0;background:#f2f4f7">'
   .'<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#f2f4f7;padding:28px 12px"><tr><td align="center">'
   .'<table role="presentation" width="600" cellpadding="0" cellspacing="0" style="max-width:600px;width:100%;background:#ffffff;border-radius:16px;overflow:hidden;font-family:Helvetica,Arial,sans-serif">'
   .'<tr><td style="background:#000b22;padding:22px 28px">'.$logo.'</td></tr>'
   .'<tr><td style="height:5px;background:#d82474;background:linear-gradient(90deg,#d82474,#f54839);font-size:0;line-height:0">&nbsp;</td></tr>'
   .'<tr><td style="padding:30px 28px 8px"><h1 style="margin:0 0 10px;font-size:21px;line-height:1.3;color:#000b22">'.$title.'</h1>'
   .'<p style="margin:0 0 18px;font-size:14.5px;line-height:1.65;color:#4d5867">'.$intro.'</p></td></tr>'
   .($table ? '<tr><td style="padding:0 28px 8px"><table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="border:1px solid #e6eaef;border-radius:10px;border-collapse:separate;overflow:hidden">'.$table.'</table></td></tr>' : '')
   .($btn ? '<tr><td style="padding:14px 28px 6px">'.$btn.'</td></tr>' : '')
   .'<tr><td style="padding:16px 28px 26px"><p style="margin:0;font-size:12.5px;line-height:1.6;color:#7a8594">'.$foot.'</p></td></tr>'
   .'</table><p style="font-family:Helvetica,Arial,sans-serif;font-size:11px;color:#9aa4b0;margin:14px 0 0">'.htmlspecialchars($siteName).' — message automatique, vous pouvez répondre directement à cet e-mail.</p>'
   .'</td></tr></table></body></html>';
}
// ---- Envoi SMTP authentifié (cPanel) quand configuré dans les Réglages ; repli automatique sur mail() ----
function smtp_send($S, $from, $to, $subjectEnc, $mimeHeaders, $body) {
  $errno = 0; $errstr = '';
  $ctx = stream_context_create(['ssl'=>['verify_peer'=>true,'verify_peer_name'=>true]]);
  $pfx = ((int)($S['port'] ?? 465) === 465) ? 'ssl://' : 'tcp://';
  $fp = @stream_socket_client($pfx.$S['host'].':'.$S['port'], $errno, $errstr, 15, STREAM_CLIENT_CONNECT, $ctx);
  if (!$fp) { $ctx2 = stream_context_create(['ssl'=>['verify_peer'=>false,'verify_peer_name'=>false]]);
    $fp = @stream_socket_client('ssl://'.$S['host'].':'.$S['port'], $errno, $errstr, 15, STREAM_CLIENT_CONNECT, $ctx2); }
  if (!$fp) return false;
  stream_set_timeout($fp, 15);
  $read = function () use ($fp) { $d = ''; while ($l = fgets($fp, 515)) { $d .= $l; if (isset($l[3]) && $l[3] === ' ') break; } return $d; };
  $cmd = function ($c, $okCodes) use ($fp, $read) { fwrite($fp, $c . "\r\n"); $r = $read(); return in_array(substr($r, 0, 3), $okCodes, true); };
  if (substr($read(), 0, 3) !== '220') { fclose($fp); return false; }
  $host = $_SERVER['SERVER_NAME'] ?? 'localhost';
  if (!$cmd("EHLO $host", ['250'])) { fclose($fp); return false; }
  if (!$cmd('AUTH LOGIN', ['334']) || !$cmd(base64_encode($S['user']), ['334']) || !$cmd(base64_encode($S['pass']), ['235'])) { fclose($fp); return false; }
  if (!$cmd("MAIL FROM:<$from>", ['250'])) { fclose($fp); return false; }
  if (!$cmd("RCPT TO:<$to>", ['250', '251'])) { fclose($fp); return false; }
  if (!$cmd('DATA', ['354'])) { fclose($fp); return false; }
  $headers = "Date: " . date('r') . "\r\n" . "To: <$to>\r\n" . "Subject: $subjectEnc\r\n"
           . "Message-ID: <" . bin2hex(random_bytes(8)) . "@" . ($_SERVER['SERVER_NAME'] ?? 'site') . ">\r\n" . $mimeHeaders;
  $data = $headers . "\r\n" . preg_replace('/^\./m', '..', str_replace(["\r\n", "\r"], "\n", $body));
  $data = str_replace("\n", "\r\n", $data);
  fwrite($fp, $data . "\r\n.\r\n");
  $ok = substr($read(), 0, 3) === '250';
  fwrite($fp, "QUIT\r\n"); fclose($fp);
  return $ok;
}
function send_multipart($to, $subject, $text, $htmlBody, $headers, $from, $enc) {
  global $cfg;
  $b = 'b' . md5(uniqid('', true));
  $h = $headers . "MIME-Version: 1.0\r\nContent-Type: multipart/alternative; boundary=\"$b\"\r\n";
  $body = "--$b\r\nContent-Type: text/plain; charset=UTF-8\r\nContent-Transfer-Encoding: 8bit\r\n\r\n$text\r\n"
        . "--$b\r\nContent-Type: text/html; charset=UTF-8\r\nContent-Transfer-Encoding: 8bit\r\n\r\n$htmlBody\r\n--$b--\r\n";
  if (!empty($cfg['SMTP_HOST']) && !empty($cfg['SMTP_USER'])) {
    $S = ['host'=>$cfg['SMTP_HOST'], 'port'=>$cfg['SMTP_PORT'] ?: 465, 'user'=>$cfg['SMTP_USER'], 'pass'=>$cfg['SMTP_PASS']];
    if (smtp_send($S, $from, $to, $enc($subject), $h, $body)) return true;
  }
  $ok = @mail($to, $enc($subject), $body, $h, "-f$from");
  if (!$ok) $ok = @mail($to, $enc($subject), $body, $h);
  return $ok;
}
$baseH = 'From: ' . $enc($fromName) . " <$from>\r\nX-Mailer: moteur-beecom\r\n";
// --- notification à l'agence
$btn = '<a href="mailto:'.($email ?: $to).'" style="display:inline-block;background:#1a73e8;color:#ffffff;text-decoration:none;font-size:14px;font-weight:bold;padding:11px 22px;border-radius:100px">Répondre à '.htmlspecialchars($nom ?: 'ce contact').'</a>';
$htmlA = gab($logo, 'Nouvelle demande : '.htmlspecialchars($sujet), 'Reçue depuis la page <b>'.htmlspecialchars($page ?: '/').'</b> le '.date('d/m/Y à H:i').'.', $rows, 'Vous recevez cet e-mail car un formulaire du site '.htmlspecialchars($siteName).' a été envoyé.', $btn, $siteName);
$ok = send_multipart($to, strtr($cfg['FORM_SUBJECT_ADMIN'], $vars), strtr($cfg['FORM_ADMIN_MESSAGE'], $vars), $htmlA, $baseH . ($email ? "Reply-To: $email\r\n" : ''), $from, $enc);
// --- accusé de réception au client
if ($email && !empty($cfg['FORM_SUBJECT_CLIENT'])) {
  $txtC = strtr($cfg['FORM_CLIENT_MESSAGE'], $vars);
  $paras = ''; foreach (preg_split('/\n\s*\n/', $txtC) as $pp) { $paras .= '<p style="margin:0 0 14px;font-size:14.5px;line-height:1.65;color:#4d5867">'.nl2br(htmlspecialchars(trim($pp))).'</p>'; }
  $htmlC = gab($logo, 'Votre demande est bien reçue', '', '', 'Cet accusé de réception a été envoyé automatiquement par '.htmlspecialchars($siteName).'.', '', $siteName);
  $htmlC = str_replace('<p style="margin:0 0 18px;font-size:14.5px;line-height:1.65;color:#4d5867"></p>', $paras, $htmlC);
  send_multipart($email, strtr($cfg['FORM_SUBJECT_CLIENT'], $vars), $txtC, $htmlC, $baseH . 'Reply-To: ' . $to . "\r\n", $from, $enc);
}
@file_put_contents(__DIR__ . '/demandes.log', date('c') . "\t" . $sujet . "\t" . $nom . "\t" . ($email ?: '-') . "\t" . str_replace(["\r","\n"], ' ', $recap) . "\n", FILE_APPEND);
echo json_encode(['success' => (bool)$ok, 'message' => $ok ? null : "L'envoi a échoué côté serveur. Écrivez-nous directement à " . $to]);
"""
def write_contact_php():
    if FORM_MODE != "php": return
    keys = ["FORM_TO", "FORM_FROM", "FORM_FROM_NAME", "FORM_SUBJECT_ADMIN", "FORM_SUBJECT_CLIENT", "FORM_CLIENT_MESSAGE", "FORM_ADMIN_MESSAGE", "SITE_NAME",
            "SMTP_HOST", "SMTP_PORT", "SMTP_USER", "SMTP_PASS"]
    extra = {"SITE_URL": CONFIG["SITE_URL"].rstrip("/"), "MAIL_LOGO": CONFIG.get("MAIL_LOGO") or next((p for p in ("/assets/img/logo-vvl-baseline-white.png", "/assets/img/logo-vfg-baseline-white.png", "/assets/img/logo-vfg-white.png", "/assets/img/logo-white.png") if asset_exists(p)), "")}
    cfg = json.dumps({**{k: CONFIG.get(k, "") for k in keys}, **extra}, ensure_ascii=False).replace("\\", "\\\\").replace("'", "\\'")
    os.makedirs(os.path.join(DIST, "api"), exist_ok=True)
    open(os.path.join(DIST, "api", "contact.php"), "w", encoding="utf-8").write(CONTACT_PHP.replace("__CFG__", cfg))
    open(os.path.join(DIST, "api", ".htaccess"), "w", encoding="utf-8").write('<Files "demandes.log">\n  Require all denied\n</Files>\n')

def heading_warnings(url, body_html):
    """Alertes de hiérarchie des titres : H1 manquant/multiple, sauts de niveau (h2 → h4)."""
    hs = [int(m.group(1)) for m in re.finditer(r"<h([1-6])\b", body_html, re.I)]
    w = []
    n1 = hs.count(1)
    if n1 == 0: w.append(f"{url} : aucun H1")
    elif n1 > 1: w.append(f"{url} : {n1} H1 (un seul recommandé)")
    prev = None
    for h in hs:
        if prev is not None and h > prev + 1:
            w.append(f"{url} : saut de niveau h{prev} → h{h}"); break
        prev = h
    return w

# ------------------------------------------------------------------ BUILD
def build(env=None):
    global ENV, IS_PREPROD, SITE_URL, ALT_FILLED
    ALT_FILLED = 0
    if env: ENV = env; IS_PREPROD = ENV == "preprod"; SITE_URL = (CONFIG["PREPROD_URL"] if IS_PREPROD else CONFIG["SITE_URL"]).rstrip("/")
    if os.path.exists(DIST): shutil.rmtree(DIST)
    os.makedirs(DIST)
    shutil.copytree(os.path.join(ROOT, "assets"), os.path.join(DIST, "assets"))
    # fichiers servis à la racine du site (favicon.ico, site.webmanifest…) : dossier root/ copié tel quel
    rootdir = os.path.join(ROOT, "root")
    if os.path.isdir(rootdir):
        for fn in sorted(os.listdir(rootdir)):
            p = os.path.join(rootdir, fn)
            if os.path.isfile(p): shutil.copy2(p, os.path.join(DIST, fn))
    index_articles()
    write_contact_php()
    urls = []
    # -------- pass 0 : inventaire des pages + carte des traductions (slugs traduits)
    entries = []
    for dp, dn, fns in os.walk(SRC):
        for fn in sorted(fns):
            if not fn.endswith(".html"): continue
            full = os.path.join(dp, fn); rel = os.path.relpath(full, SRC)
            meta, body = parse(full)
            entries.append((rel, url_from_path(rel), meta, body))
    global TRANS_URLS; TRANS_URLS.clear()
    others = [c.strip() for c, _ in LANGS if c.strip() != DEFAULT_LANG]
    trs = {}
    if others:
        import translate as TR
        for lang in others:
            mp = {}
            for rel, url, meta, body in entries:
                if meta.get("draft", "false").lower() == "true": continue
                bd = load_blocks(rel)
                units = TR.page_units(meta, bd) + (TR.body_extra_units(body) if bd else [("body", body)])
                tr = TR.load(blocks_key(rel), lang)
                if TR.is_complete(units, tr):
                    path = (tr.get("path") if tr.get("path") is not None else url.strip("/"))
                    lurl = f"/{lang}/" + (path.strip("/") + "/" if path.strip("/") else "")
                    mp[url] = lurl; trs[(rel, lang)] = tr
            if mp: TRANS_URLS[lang] = mp
            # menu traduit : matérialiser blocks/_menu.<lang>.json depuis translations/_menu.<lang>.json
            mtr = TR.load("_menu", lang); menu_p = os.path.join(BLOCKS_DIR, "_menu.json")
            if mtr.get("units") and os.path.exists(menu_p):
                menu = json.load(open(menu_p, encoding="utf-8"))
                menu2 = TR.overlay_blocks(menu, mtr)
                json.dump(menu2, open(os.path.join(BLOCKS_DIR, f"_menu.{lang}.json"), "w", encoding="utf-8"), ensure_ascii=False, indent=1)
    # -------- pass 1 : pages françaises
    has_404_page = False
    hwarns = []
    for rel, url, meta, body in entries:
        b2 = apply_blocks(body, rel)
        if rel != "404.html" and meta.get("noindex", "false").lower() != "true":
            hwarns += heading_warnings(url, b2)
        if rel == "404.html":   # page 404 importée : fichier plat à la racine, jamais dans le sitemap
            has_404_page = True
            with open(os.path.join(DIST, "404.html"), "w", encoding="utf-8") as f:
                f.write(render(meta, b2, "/404/"))
            continue
        out_dir = os.path.join(DIST, url.strip("/"))
        os.makedirs(out_dir, exist_ok=True)
        with open(os.path.join(out_dir, "index.html"), "w", encoding="utf-8") as f:
            f.write(render(meta, b2, url))
        if meta.get("noindex", "false").lower() != "true":
            lm = meta.get("modified") or meta.get("date") or datetime.date.fromtimestamp(os.path.getmtime(os.path.join(SRC, rel))).isoformat()
            urls.append((url, meta.get("priority", "0.7"), lm))
    # -------- pass 2 : pages traduites
    if others:
        import translate as TR
        for lang in TRANS_URLS:
            for rel, url, meta, body in entries:
                if url not in TRANS_URLS[lang]: continue
                tr = trs[(rel, lang)]
                meta2 = TR.overlay_meta(meta, tr); meta2["lang"] = lang; meta2["_fr_url"] = url
                bd = load_blocks(rel)
                if bd: b2 = TR.overlay_body_extras(apply_blocks(body, rel, TR.overlay_blocks(bd, tr)), tr)
                else: b2 = TR.get_body(tr) or body
                lurl = TRANS_URLS[lang][url]
                out_dir = os.path.join(DIST, lurl.strip("/"))
                os.makedirs(out_dir, exist_ok=True)
                with open(os.path.join(out_dir, "index.html"), "w", encoding="utf-8") as f:
                    f.write(render(meta2, b2, lurl))
                if meta.get("noindex", "false").lower() != "true":
                    lm = meta.get("modified") or meta.get("date") or datetime.date.fromtimestamp(os.path.getmtime(os.path.join(SRC, rel))).isoformat()
                    urls.append((lurl, meta.get("priority", "0.7"), lm))
    # sitemap + robots
    with open(os.path.join(DIST, "sitemap.xml"), "w", encoding="utf-8") as f:
        f.write('<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n')
        for u, p, d in sorted(urls):
            f.write(f"  <url><loc>{SITE_URL}{u}</loc><lastmod>{d}</lastmod></url>\n")   # priority retirée (ignorée par Google)
        f.write("</urlset>\n")
    with open(os.path.join(DIST, "robots.txt"), "w") as f:
        if IS_PREPROD: f.write("User-agent: *\nDisallow: /\n")
        elif (CONFIG.get("ROBOTS_TXT") or "").strip(): f.write(CONFIG["ROBOTS_TXT"].strip() + "\n")
        else: f.write(f"User-agent: *\nAllow: /\nSitemap: {SITE_URL}/sitemap.xml\n")
    home_meta = next((m for r_, u_, m, b_ in entries if u_ == "/"), {})
    if not IS_PREPROD and home_meta.get("noindex", "false").lower() == "true":
        print("⚠ ATTENTION : la page d'ACCUEIL est en noindex — elle ne sera pas indexée par Google.")
    # 404 (par défaut, si le site n'a pas sa propre page 404 importée)
    if not has_404_page:
      with open(os.path.join(DIST, "404.html"), "w", encoding="utf-8") as f:
        f.write(render({"title": "Page introuvable — " + SITE_NAME, "noindex": "true"},
                       '<section class="section center container-narrow"><h1>Oups, cette page n\'existe pas.</h1><p class="intro">Elle a peut-être été déplacée. Le plus utile à faire maintenant : <a href="/audit-gratuit/">demander l\'audit gratuit de votre fiche Google</a> ou <a href="/">revenir à l\'accueil</a>.</p></section>', "/404/"))
    # .htaccess (Apache/OVH) : URLs propres + cache + 404
    redirects = []
    if os.path.exists(REDIRECTS_PATH):
        try: redirects = [r for r in json.load(open(REDIRECTS_PATH, encoding="utf-8")) if r.get("from") and (r.get("to") or str(r.get("code")) == "410")]
        except Exception as e: print("⚠ redirects.json illisible :", e)
    # --- langues retirées des Réglages : les anciennes URLs traduites déjà en ligne sont redirigées (301)
    #     vers la page française équivalente (pas de 404, pas de contenu obsolète indexé, pas de cul-de-sac).
    #     Les fichiers translations/ sont conservés : remettre la langue dans Réglages la réactive telle quelle.
    lang_catchall = []
    tdir = os.path.join(ROOT, "translations")
    if os.path.isdir(tdir):
        active = {DEFAULT_LANG} | {c.strip() for c, _ in LANGS}
        removed = {}
        for fn in sorted(os.listdir(tdir)):
            m = re.match(r"^(.+)\.([a-z]{2}(?:-[a-z]{2})?)\.json$", fn)
            if m and m.group(2) not in active and not m.group(1).startswith("_"):
                removed.setdefault(m.group(2), []).append(m.group(1))
        if removed:
            fr_urls = {re.sub(r"\.html$", "", rel.replace(os.sep, "/")).replace("/", "__"): url for rel, url, _m, _b in entries}
            for lang, names in sorted(removed.items()):
                entries_l = []
                for name in names:
                    fr = fr_urls.get(name)
                    if not fr: continue
                    try: tr = json.load(open(os.path.join(tdir, f"{name}.{lang}.json"), encoding="utf-8"))
                    except Exception: tr = {}
                    path = tr.get("path") if tr.get("path") is not None else fr.strip("/")
                    lurl = f"/{lang}/" + (path.strip("/") + "/" if path.strip("/") else "")
                    if lurl != f"/{lang}/": entries_l.append({"from": lurl, "to": fr, "code": "301"})
                # les plus spécifiques d'abord (Redirect d'Apache s'applique par préfixe, premier arrivé servi)
                entries_l.sort(key=lambda r: -len(r["from"]))
                redirects += entries_l
                lang_catchall.append(lang)
                print(f"ℹ Langue retirée « {lang} » : {len(entries_l)} redirection(s) 301 vers les pages françaises + règle générale /{lang}/… → / (traductions conservées dans translations/).")
    with open(os.path.join(DIST, "_redirects"), "w") as f:      # Netlify / Cloudflare Pages
        for r in redirects:
            c = str(r.get("code", "301"))
            f.write(f'{r["from"]}  {r["to"] or "/"}  {c}\n')
        for lg in lang_catchall:
            f.write(f'/{lg}/*  /  301\n')
    with open(os.path.join(DIST, ".htaccess"), "w") as f:
        if IS_PREPROD:
            f.write("Header set X-Robots-Tag \"noindex, nofollow\"\n")
            if CONFIG.get("PREPROD_PASS"):
                import hashlib, base64
                # chemin absolu du dossier préprod sur le serveur : DOCROOT_PREPROD (mode copie)
                # sinon SERVER_HOME + FTP_DIR_PREPROD (mode FTP)
                pdir = (CONFIG.get("DOCROOT_PREPROD") or "").strip().rstrip("/")
                if not pdir and CONFIG.get("SERVER_HOME") and CONFIG.get("FTP_DIR_PREPROD"):
                    pdir = CONFIG["SERVER_HOME"].rstrip("/") + "/" + CONFIG["FTP_DIR_PREPROD"].strip("/")
                digest = "{SHA}" + base64.b64encode(hashlib.sha1(CONFIG["PREPROD_PASS"].encode()).digest()).decode()
                open(os.path.join(DIST, ".htpasswd"), "w").write(f'{CONFIG.get("PREPROD_USER") or "preprod"}:{digest}\n')
                if pdir:
                    f.write("AuthType Basic\nAuthName \"Acces restreint - preprod\"\nAuthUserFile " + pdir + "/.htpasswd\nRequire valid-user\n")
                else:
                    f.write("# PROTECTION PREPROD NON ACTIVE : renseignez dans Reglages > Publication le\n"
                            "# \"Dossier public de la preprod\" (chemin absolu sur le serveur, ex. /home/compte/dev.mon-domaine.fr)\n"
                            "# ou le \"Chemin du compte serveur\" + \"Dossier FTP de la preprod\", puis regenerez.\n"
                            "# Vous pouvez aussi decommenter ces 3 lignes en corrigeant le chemin :\n"
                            "# AuthType Basic\n# AuthName \"Acces restreint - preprod\"\n"
                            "# AuthUserFile /CHEMIN/ABSOLU/DU/DOSSIER/PREPROD/.htpasswd\n# Require valid-user\n")
                    print("⚠ PRÉPROD : mot de passe défini mais chemin serveur inconnu — protection .htaccess NON active.")
                    print("  → Réglages › Publication : renseignez « Dossier public de la préprod » (chemin absolu), puis régénérez.")
            elif CONFIG.get("PREPROD_URL"):
                print("⚠ PRÉPROD sans mot de passe : la préprod sera accessible à tous (noindex seulement).")
                print("  → Réglages › Publication : définissez un identifiant + mot de passe de protection de la préprod.")
        for r in redirects:
            c = str(r.get("code", "301"))
            if c == "410": f.write(f'Redirect gone {r["from"]}\n')
            else: f.write(f'Redirect {c} {r["from"]} {r["to"]}\n')
        for lg in lang_catchall:   # langue retirée : tout le reste de /<lang>/… retombe sur l'accueil (301)
            f.write(f'RedirectMatch 301 ^/{lg}(/.*)?$ /\n')
        # domaine canonique : https + www ou sans-www selon l'URL publique des Réglages,
        # en UNE seule 301 (pas de chaîne) ; les hôtes preprod.* / dev.* ne sont jamais réécrits
        prod_host = CONFIG["SITE_URL"].rstrip("/").split("//", 1)[-1]
        pre_host = (CONFIG.get("PREPROD_URL") or "").rstrip("/").split("//", 1)[-1]
        pre_sub = (pre_host.split(".", 1)[0] + "\\.") if pre_host else "preprod\\."
        if prod_host.startswith("www."):
            canon = (f"RewriteCond %{{HTTP_HOST}} !^{pre_sub} [NC]\n"
                     "RewriteCond %{HTTPS} off [OR]\n"
                     "RewriteCond %{HTTP_HOST} !^www\\. [NC]\n"
                     "RewriteCond %{HTTP_HOST} ^(?:www\\.)?(.+)$ [NC]\n"
                     "RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L]\n")
        else:
            canon = (f"RewriteCond %{{HTTP_HOST}} !^{pre_sub} [NC]\n"
                     "RewriteCond %{HTTPS} off [OR]\n"
                     "RewriteCond %{HTTP_HOST} ^www\\. [NC]\n"
                     "RewriteCond %{HTTP_HOST} ^(?:www\\.)?(.+)$ [NC]\n"
                     "RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L]\n")
        f.write("""ErrorDocument 404 /404.html
Options -Indexes
AddDefaultCharset UTF-8

<IfModule mod_rewrite.c>
RewriteEngine On
""" + canon + """# /dossier/index.html -> /dossier/  (une seule URL par page)
RewriteCond %{THE_REQUEST} \\s/+(.*/)?index\\.html[\\s?] [NC]
RewriteRule ^(.*/)?index\\.html$ /$1 [R=301,L]
# /page -> /page/ quand le dossier existe
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.+[^/])$ /$1/ [R=301,L]
</IfModule>

<IfModule mod_mime.c>
AddType application/manifest+json .webmanifest
AddType image/x-icon .ico
AddType image/webp .webp
AddType image/svg+xml .svg
</IfModule>

<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/webp "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/svg+xml "access plus 1 year"
ExpiresByType image/x-icon "access plus 1 year"
ExpiresByType font/woff2 "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/javascript "access plus 1 month"
ExpiresByType application/manifest+json "access plus 1 week"
ExpiresByType text/html "access plus 0 seconds"
</IfModule>

<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/css application/javascript application/json application/xml image/svg+xml application/manifest+json
</IfModule>

<IfModule mod_headers.c>
Header always set X-Content-Type-Options "nosniff"
Header always set X-Frame-Options "SAMEORIGIN"
Header always set Referrer-Policy "strict-origin-when-cross-origin"
Header always set Permissions-Policy "camera=(), microphone=(), geolocation=()"
Header always set X-Bcm "__BCMID__"
<FilesMatch "\\.(webp|png|jpe?g|svg|ico|css|js|woff2?)$">
Header set Cache-Control "public, max-age=31536000, immutable"
</FilesMatch>
</IfModule>
""")
    _hp = os.path.join(DIST, ".htaccess")
    _ht = open(_hp, encoding="utf-8").read()
    open(_hp, "w", encoding="utf-8").write(_ht.replace("__BCMID__", BCM_ID))
    if hwarns:
        print(f"⚠ Hiérarchie des titres — {len(hwarns)} alerte(s) :")
        for w in hwarns[:8]: print("   - " + w)
        if len(hwarns) > 8: print(f"   … et {len(hwarns) - 8} autre(s).")
    if ALT_FILLED:
        print(f"ℹ {ALT_FILLED} image(s) publiée(s) avec un alt de secours (nom de fichier) — pour de vraies descriptions : Images › « Générer les ALT manquants (IA) ».")
    print(f"✔ {len(urls)} pages générées dans dist/ — mode {'PRÉPROD (noindex' + (', mot de passe' if CONFIG.get('PREPROD_PASS') else '') + ')' if IS_PREPROD else 'PRODUCTION (indexable)'} · {SITE_URL} · {len(ARTICLES)} articles, {len(redirects)} redirections")
    return len(urls)

if __name__ == "__main__":
    build()
