"""Supprime les refus reCAPTCHA des FormProcessor.php : la demande part,
marquee [A VERIFIER - reCAPTCHA ...] dans le sujet.
Usage : python3 fix_fp.py [--apply] fichier...
"""
import re, sys, shutil, os

apply = "--apply" in sys.argv
files = [a for a in sys.argv[1:] if a != "--apply"]
SUFFIX = ".bak-recaptcha-20261106"
MARK = "fp-rc-20261106"

die_re = re.compile(r"die\(\s*\$this->_getErrorResponse\(\s*('[^']*'|\$this->_t\(\s*'[^']*'\s*\)|\$this->_messages\[\s*'[^']*'\s*\])\s*\)\s*\);")
subj_re = re.compile(r"(\n([ \t]*)\$subject\s*=\s*\$form\['subject'\];[^\n]*\n)")

for f in files:
    if "/expertvidemaison.be/" in f:
        print("SKIP interdit", f); continue
    s = open(f, encoding="utf-8", errors="surrogateescape").read()
    if MARK in s:
        print("DEJA", f); continue
    m = re.search(r"private function _checkRecaptcha\(.*?\n[ \t]*(?:private|public|protected) (?:static )?function ", s, re.S)
    if not m:
        print("PAS_DE_FONCTION", f); continue
    body = m.group(0)
    def rep(mm):
        before = mm.string[max(0, mm.start() - 160):mm.start()]
        if "score" in before:
            reason = "score bas"
        elif "empty($response)" in before:
            reason = "jeton absent"
        else:
            reason = "verification echouee"
        return ("{ /* %s */ $GLOBALS['FP_RC_FLAG'] = '%s' . (isset($resp->score) ? ' ' . $resp->score : ''); return; }"
                % (MARK, reason))
    nb, n = die_re.subn(rep, body)
    sm = subj_re.search(s)
    if n == 0 or not sm:
        print("ANCRE_MANQUANTE die=%d subject=%s %s" % (n, bool(sm), f)); continue
    s2 = s.replace(body, nb, 1)
    ind = sm.group(2)
    add = (ind + "/* %s */ if (!empty($GLOBALS['FP_RC_FLAG'])) { $subject = '[A VERIFIER - reCAPTCHA ' . $GLOBALS['FP_RC_FLAG'] . '] ' . $subject; }\n" % MARK)
    s2 = s2.replace(sm.group(1), sm.group(1) + add, 1)
    print("OK die=%d %s" % (n, f))
    if apply:
        shutil.copy2(f, f + SUFFIX)
        with open(f, "r+", encoding="utf-8", errors="surrogateescape") as fh:  # garde inode/proprietaire
            fh.seek(0); fh.write(s2); fh.truncate()
