"""Formulaires « Please wait for reCAPTCHA to load » : ne plus bloquer l'envoi.
1) alerte -> envoi de secours apres 2,5 s si reCAPTCHA absent
2) <form id=X> sans action -> action = URL du fetch() de la page
Usage : python3 fix_alert.py [--apply] fichier...
"""
import re, sys, shutil
APPLY = "--apply" in sys.argv
TAG = "fix-form-20261106"

alert_re = re.compile(
    r"if\s*\(\s*!window\.grecaptcha\s*\)\s*\{\s*alert\(\s*'Please wait for reCAPTCHA to load'\s*\)\s*;?\s*return\s*;?\s*\}")
handler_re = re.compile(
    r"getElementById\(\s*'([\w-]+)'\s*\)\.addEventListener\(\s*'submit'\s*,\s*function\s*\(\s*(\w+)\s*\)")
fetch_re = re.compile(r"fetch\(\s*'([^']+\.php)'")

for f in [a for a in sys.argv[1:] if a != "--apply"]:
    s = open(f, encoding="utf-8", errors="surrogateescape").read()
    if TAG + "-alert" in s:
        print("DEJA", f); continue
    am = list(alert_re.finditer(s))
    hm = handler_re.search(s)
    fm = fetch_re.findall(s)
    if len(am) != 1 or not hm or len(set(fm)) != 1:
        print("SKIP alert=%d handler=%s fetch=%s %s" % (len(am), bool(hm), sorted(set(fm)), f)); continue
    form_id, ev = hm.group(1), hm.group(2)
    endpoint = fm[0]
    new_alert = ("if (!window.grecaptcha) { /* %s-alert */ var __f = %s.target;"
                 " try { if (typeof loadRecaptcha === 'function') loadRecaptcha(); } catch (__x) {}"
                 " setTimeout(function () { if (!window.grecaptcha) { __f.submit(); }"
                 " else { __f.dispatchEvent(new Event('submit', { cancelable: true })); } }, 2500); return; }"
                 % (TAG, ev))
    s2 = s[:am[0].start()] + new_alert + s[am[0].end():]
    # action du formulaire
    form_re = re.compile(r"<form\b[^>]*\bid=\"%s\"[^>]*>" % re.escape(form_id))
    forms = form_re.findall(s2)
    note = "action=deja"
    if len(forms) == 1 and "action=" not in forms[0]:
        tag = forms[0]
        s2 = s2.replace(tag, tag[:-1].rstrip() + ' action="%s">' % endpoint, 1)
        note = "action+" + endpoint
    elif len(forms) != 1:
        note = "form?%d" % len(forms)
    print("OK", note, f)
    if APPLY:
        shutil.copy2(f, f + ".bak-form-20261106")
        with open(f, "r+", encoding="utf-8", errors="surrogateescape") as fh:
            fh.seek(0); fh.write(s2); fh.truncate()
