import os
import re
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]

FILE_EXTS = {".php", ".html", ".htm"}

RE_BROKEN_PHP = re.compile(r"<\.php\?php", re.IGNORECASE)
RE_TEL_PHP = re.compile(r'(href\s*=\s*["\']tel:[^"\']*?)\.php(["\'])', re.IGNORECASE)


def iter_targets():
    for dirpath, dirnames, filenames in os.walk(ROOT):
        dirnames[:] = [d for d in dirnames if d not in {"_next", "__website-next", "cdn-cgi", "node_modules"}]
        for fn in filenames:
            p = Path(dirpath) / fn
            if p.suffix.lower() in FILE_EXTS:
                yield p


def main():
    changed = 0
    changed_files = []

    for p in iter_targets():
        try:
            original = p.read_text(encoding="utf-8", errors="ignore")
        except Exception:
            continue

        updated = original
        updated = RE_BROKEN_PHP.sub("<?php", updated)
        updated = RE_TEL_PHP.sub(r"\1\2", updated)

        if updated != original:
            try:
                p.write_text(updated, encoding="utf-8")
                changed += 1
                changed_files.append(str(p.relative_to(ROOT)))
            except Exception:
                pass

    print(f"Updated files: {changed}")
    for f in changed_files[:200]:
        print(f"- {f}")
    if len(changed_files) > 200:
        print("... truncated ...")


if __name__ == "__main__":
    main()

