"""Retire la marque « AAB » d'un site qui ne s'appelle pas AAB (18/11/2026).
Usage : python3 deab.py <dossier> "<Marque>" [php] [--apply]
Ne touche pas aux attributs (src, href, alt...), aux commentaires PHP, ni aux mentions légales (AAB SRL/SPRL/BV, BCE)."""
import os, re, sys, shutil, subprocess
base, brand = sys.argv[1], sys.argv[2]
PHP = sys.argv[3] if len(sys.argv) > 3 and not sys.argv[3].startswith("--") else "php"
APPLY = "--apply" in sys.argv
BAK = ".bak-aab-20261118"
SKIP = re.compile(r"/(?:vendor|node_modules|storage|backup[^/]*|old|back|tools|scripts|quarantine[^/]*)(?:/|$)")
RULES = [
    (r"AAB Services\s*[-–|]\s*" + re.escape(brand), brand),
    (r"AAB\s+" + re.escape(brand), brand),
    (r"AAB [Hh]uizen leegmaken", "Huizen leegmaken"),
    (r"AAB (?:Services|Brocanteur|déménagement|Déménagement|Demenagement)", brand),
    (r"\s*[-–|]\s*AAB(?=\s*(?:<|$|\"|'))", ""),
    (r"bedankt AAB", "bedankt"),
    (r"AAB Débarras [A-ZÀ-Ý][\w-]+", brand),
    (r"(?<![\w/@.\-])AAB(?![\w@.\-])(?!\s*(?:SRL|SPRL|BV|BVBA|SA|NV))", brand),
]
ATTR = re.compile(r"""(?i)\b(?:src|href|srcset|data-[\w-]+|action|id|class|name|for)\s*=\s*(?:"[^"]*"|'[^']*')|url\([^)]*\)|[\w./-]+\.(?:webp|jpe?g|png|svg|gif|php|html?)\b|[\w.+-]+@[\w.-]+""")
tot = 0
for dp, dn, fn in os.walk(base):
    if SKIP.search(dp[len(base):]): dn[:] = []; continue
    for f in fn:
        if not f.endswith((".php", ".html", ".htm", ".txt", ".json")) or ".bak" in f or re.match(r"\d{3,}", f): continue
        p = os.path.join(dp, f)
        try: t = open(p, encoding="utf8").read()
        except Exception: continue
        if not re.search(r"\bAAB\b", t): continue
        masks = []
        def mk(m):
            masks.append(m.group(0)); return "<§M%d§>" % (len(masks) - 1)
        tm = re.sub(r"(?s)<!--.*?-->", mk, t)
        if p.endswith(".php"): tm = re.sub(r"(?ms)/\*.*?\*/|^[ \t]*//[^\n]*", mk, tm)
        tm = ATTR.sub(mk, tm)
        n = 0
        for a, b in RULES:
            tm, c = re.subn(a, b, tm); n += c
        for _ in range(5):
            if "<§M" not in tm: break
            tm = re.sub(r"<§M(\d+)§>", lambda m: masks[int(m.group(1))], tm)
        if tm == t: continue
        if p.endswith(".php"):
            tmp = "/tmp/_deab_%d.php" % os.getpid(); open(tmp, "w", encoding="utf8").write(tm)
            ok = subprocess.run([PHP, "-l", tmp], capture_output=True).returncode == 0; os.remove(tmp)
            if not ok: print("SYNTAXE", p); continue
        tot += n
        print(n, p[len(base):])
        if APPLY:
            if not os.path.exists(p + BAK): shutil.copy2(p, p + BAK)
            open(p, "w", encoding="utf8").write(tm)
print("TOTAL", tot, "APPLY" if APPLY else "DRY")
