#!/usr/bin/env python3
"""Cross-reference every #id referenced in page JS against the HTML file."""
import re, sys, pathlib

BASE = pathlib.Path(__file__).resolve().parent.parent / "static"
PAGES = {
    "index": ("index.html", "js/pages/index.js"),
    "login": ("login.html", "js/pages/login.js"),
    "campaigns": ("campaigns.html", "js/pages/campaigns.js"),
    "gmail-accounts": ("gmail-accounts.html", "js/pages/gmail-accounts.js"),
    "recipients": ("recipients.html", "js/pages/recipients.js"),
    "send-test": ("send-test.html", "js/pages/send-test.js"),
    "logs": ("logs.html", "js/pages/logs.js"),
    "subjects": ("subjects.html", "js/pages/subjects.js"),
    "templates": ("templates.html", "js/pages/templates.js"),
    "saved-templates": ("saved-templates.html", "js/pages/saved-templates.js"),
    "attachments": ("attachments.html", "js/pages/attachments.js"),
    "phones": ("phones.html", "js/pages/phones.js"),
    "suppression": ("suppression.html", "js/pages/suppression.js"),
    "settings": ("settings.html", "js/pages/settings.js"),
}

ID_REF = re.compile(r"""[\$]\(\s*["']#([A-Za-z0-9_-]+)["']\s*[,)]""")
ID_DEF = re.compile(r"""id=["']([A-Za-z0-9_-]+)["']""")

fail = 0
for name, (html_rel, js_rel) in PAGES.items():
    html = (BASE / html_rel).read_text()
    js = (BASE / js_rel).read_text()
    defined = set(ID_DEF.findall(html))
    referenced = set(ID_REF.findall(js))
    missing = sorted(r for r in referenced if r not in defined)
    if missing:
        fail += 1
        print(f"[MISSING] {name}: HTML {html_rel} lacks ids used by JS: {missing}")
    else:
        print(f"[ok] {name}")
sys.exit(1 if fail else 0)
