import re
import pathlib
import sys

sys.path.insert(0, r"c:\Projects\FreeExile")
if hasattr(sys.stdout, "reconfigure"):
    sys.stdout.reconfigure(encoding="utf-8")
    sys.stderr.reconfigure(encoding="utf-8")

from tests.e2e.test_ui_typography_i18n_wiki_streamlining_e2e import clean_words, has_bilingual_parens

root = pathlib.Path(r"c:\Projects\FreeExile")
webapp = root / "client" / "webapp"
tpl_dir = webapp / "js" / "ui" / "templates"

files = [webapp / "index.html"] + list(tpl_dir.glob("*.js"))

def strip_html_comments(text: str) -> str:
    return re.sub(r'<!--.*?-->', '', text, flags=re.DOTALL)

print("=" * 80)
print("AUDIT: VISIBLE UI CONTROLS & BILINGUAL STRINGS")
print("=" * 80)

total_buttons = 0
long_buttons = []
bilingual_buttons = []
bilingual_labels = []
bilingual_headings = []

for f in files:
    content = f.read_text(encoding="utf-8")
    content_no_comments = strip_html_comments(content)
    
    # 1. Buttons
    buttons = re.findall(r'<button\b([^>]*)>(.*?)</button>', content_no_comments, re.DOTALL)
    for attrs, inner in buttons:
        total_buttons += 1
        id_m = re.search(r'id=["\']([^"\']+)["\']', attrs)
        bid = id_m.group(1) if id_m else "no-id"
        w = clean_words(inner)
        raw_text = re.sub(r'<[^>]+>', ' ', inner).strip()
        
        # Check > 2 words
        if len(w) > 2:
            long_buttons.append((f.name, bid, raw_text, w))
            
        # Check parens like (Mở 6 Cổng Tế Xương) or (English)
        parens = re.findall(r'\(([^\)]+)\)', raw_text)
        if parens:
            for p in parens:
                p_clean = p.strip()
                if len(p_clean) > 2 and not p_clean.isdigit():
                    bilingual_buttons.append((f.name, bid, raw_text, p_clean))

    # 2. Labels, H1-H6, Spans with bilingual pattern
    for tag in ["label", "h1", "h2", "h3", "h4", "h5", "h6"]:
        items = re.findall(rf'<{tag}\b([^>]*)>(.*?)</{tag}>', content_no_comments, re.DOTALL)
        for attrs, inner in items:
            raw_text = re.sub(r'<[^>]+>', ' ', inner).strip()
            parens = re.findall(r'\(([A-Za-z\s]{3,})\)', raw_text)
            if parens:
                bilingual_labels.append((f.name, tag, raw_text, parens))

print(f"\n1. TOTAL BUTTONS EVALUATED: {total_buttons}")
print(f"Buttons with > 2 words: {len(long_buttons)}")
for fname, bid, raw, w in long_buttons:
    print(f"  - [{fname}] id='{bid}' -> words({len(w)}): {w} | raw: '{raw}'")

print(f"\n2. BUTTONS WITH PARENTHETICAL CONTENT: {len(bilingual_buttons)}")
for fname, bid, raw, p in bilingual_buttons:
    print(f"  - [{fname}] id='{bid}' -> paren: '({p})' | raw: '{raw}'")

print(f"\n3. HEADINGS/LABELS WITH BILINGUAL PARENS: {len(bilingual_labels)}")
for fname, tag, raw, p in bilingual_labels:
    print(f"  - [{fname}] <{tag}> -> parens: {p} | text: '{raw}'")
