# Ajoute alt aux <img> qui n'en ont pas (24/11/2026). Usage : python3 fix_alt.py [--ecrire] dossier "Nom du site"
# logo -> « Logo <Nom> » ; autres -> texte du <h1> du fichier (sinon <title>, sinon Nom). Sauvegarde .bak-bing-20261124.
import os, re, sys, html, shutil
W = '--ecrire' in sys.argv
args = [a for a in sys.argv[1:] if a != '--ecrire']
root, brand = args[0], args[1]
SKIP = re.compile(r'(?i)(\.bak|bak-|quarantine|backup|/old|vendor|node_modules|/admin|wp-admin|\$)')
tot_f = tot_i = 0
for dp, dn, fn in os.walk(root):
    dn[:] = [d for d in dn if not SKIP.search('/' + d)]
    if dp.count(os.sep) - root.count(os.sep) > 3: continue
    for f in fn:
        if not re.search(r'\.(html?|php)$', f) or SKIP.search(f): continue
        p = os.path.join(dp, f)
        try: s = open(p, encoding='utf-8').read()
        except Exception: continue
        def txt(tag):
            m = re.search(rf'(?is)<{tag}[^>]*>(.*?)</{tag}>', s)
            if not m or '<?' in m.group(1): return ''
            t = html.unescape(re.sub(r'<[^>]+>', ' ', m.group(1)))
            return re.sub(r'\s+', ' ', t).strip()[:100]
        label = txt('h1') or txt('title') or brand
        if re.search(r'(?i)introuvable|not found|404|niet gevonden', label): label = brand
        cnt = [0]
        def rep(m):
            tag = m.group(0)
            if re.search(r'(?i)\salt\s*=', tag) or '<?' in tag: return tag
            cnt[0] += 1
            logo = re.search(r'(?i)logo', tag)
            a = ('Logo ' + brand) if logo else label
            return re.sub(r'(?i)^<img\b', '<img alt="' + html.escape(a, quote=True) + '"', tag)
        s2 = re.sub(r'(?is)<img\b[^>]*>', rep, s)
        n = cnt[0]
        if n:
            tot_f += 1; tot_i += n
            print(p.replace(root, ''), n, '->', label[:50])
            if W:
                if not os.path.exists(p + '.bak-bing-20261124'): shutil.copy2(p, p + '.bak-bing-20261124')
                open(p, 'w', encoding='utf-8').write(s2)
print('TOTAL', tot_f, 'fichiers', tot_i, 'images', 'ÉCRIT' if W else '(essai)')
