# -*- coding: utf-8 -*-
"""Native-confirm gate (drill F-11) — native confirm()/prompt() dialogs are OS-modals that block
browser automation (CDP freezes) and are banned from the UI; consequential actions use the inline
felhomConfirm helper (layout.html) or the .confirm-overlay dialog.

Run from controller/:  python scripts/native_confirm_gate.py
Exit 1 if any native confirm(/prompt( call remains in the templates.
"""
import io, os, re, sys

ROOTS = [
    os.path.join("internal", "web", "templates"),
    os.path.join("internal", "setup", "templates"),
]

# A bare confirm(/prompt( CALL with an argument: not preceded by an identifier character, so felhomConfirm( and
# onRestoreConfirmChange( never match. window.confirm( still matches ('.' is not identifier).
NATIVE = re.compile(r"(?<![A-Za-z0-9_$])(?:confirm|prompt)\(\s*[^)\s]")


def main():
    total = 0
    for root in ROOTS:
        for fn in sorted(os.listdir(root)):
            if not fn.endswith(".html"):
                continue
            path = os.path.join(root, fn)
            for lineno, line in enumerate(io.open(path, encoding="utf-8"), 1):
                if NATIVE.search(line):
                    total += 1
                    print("%s:%d  %s" % (fn, lineno, line.strip()[:120].encode('ascii', 'backslashreplace').decode()))
    if total:
        print("NATIVE CONFIRM GATE FAILED: %d native confirm()/prompt() call(s) remain" % total)
        sys.exit(1)
    print("native-confirm gate OK — no native confirm()/prompt() in templates")


if __name__ == "__main__":
    main()
