import re
import pathlib
import sys

# Add project root to sys.path
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, get_template_buttons, has_bilingual_parens

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

# 1. index.html
html = (webapp / "index.html").read_text(encoding="utf-8")
btns_html = re.findall(r'<button\b([^>]*)>(.*?)</button>', html, re.DOTALL)
print(f"=== index.html (Total buttons: {len(btns_html)}) ===")
long_html = []
bilingual_html = []
for attrs, inner in btns_html:
    words = clean_words(inner)
    id_m = re.search(r'id=["\']([^"\']+)["\']', attrs)
    bid = id_m.group(1) if id_m else "no-id"
    if len(words) > 2:
        long_html.append((bid, inner.strip(), words))
    if has_bilingual_parens(inner):
        bilingual_html.append((bid, inner.strip()))

print(f"Buttons in index.html > 2 words: {len(long_html)}")
for bid, raw, w in long_html:
    print(f"  [{bid}] words({len(w)}): {w} (raw: {raw[:60]})")

print(f"Buttons in index.html bilingual: {len(bilingual_html)}")
for bid, raw in bilingual_html:
    print(f"  [{bid}] raw: {raw}")

# Also check other interactive controls (select, a, tab-like buttons) in index.html
selects_html = re.findall(r'<select\b([^>]*)>(.*?)</select>', html, re.DOTALL)
print(f"\nSelect elements in index.html: {len(selects_html)}")
for attrs, inner in selects_html:
    options = re.findall(r'<option\b[^>]*>(.*?)</option>', inner)
    print(f"  Options: {options}")

# Check tooltip titles and descs in index.html
tooltip_titles = re.findall(r'data-tooltip-title=["\']([^"\']+)["\']', html)
bilingual_tt = [t for t in tooltip_titles if has_bilingual_parens(t)]
print(f"\nTooltip titles in index.html: {len(tooltip_titles)}, bilingual: {len(bilingual_tt)}")
for t in bilingual_tt:
    print(f"  Bilingual tooltip title: {t}")

tooltip_descs = re.findall(r'data-tooltip-desc=["\']([^"\']+)["\']', html)
multi_sentence_tt = [d for d in tooltip_descs if d.count(".") > 1]
print(f"Tooltip descs in index.html: {len(tooltip_descs)}, multi-sentence: {len(multi_sentence_tt)}")
for d in multi_sentence_tt:
    print(f"  Multi-sentence: {d}")

# 2. Template catalogs
tpl_dir = webapp / "js" / "ui" / "templates"
print("\n=== Template Catalogs ===")
total_template_buttons = 0
total_long_template_buttons = 0
total_bilingual_template_buttons = 0

for tpl in sorted(tpl_dir.glob("*.js")):
    btns = get_template_buttons(tpl.name)
    total_template_buttons += len(btns)
    long_tpl = []
    bilingual_tpl = []
    for b in btns:
        w = clean_words(b["text"])
        if len(w) > 2:
            long_tpl.append((b["id"], b["text"], w))
        if has_bilingual_parens(b["text"]):
            bilingual_tpl.append((b["id"], b["text"]))
    total_long_template_buttons += len(long_tpl)
    total_bilingual_template_buttons += len(bilingual_tpl)
    print(f"{tpl.name}: {len(btns)} buttons | {len(long_tpl)} > 2 words | {len(bilingual_tpl)} bilingual")
    for bid, raw, w in long_tpl:
        print(f"  >2w: [{bid}] ({len(w)} words) {w} (raw: {raw[:60]})")
    for bid, raw in bilingual_tpl:
        print(f"  bilingual: [{bid}] raw: {raw}")

# Check navigation tabs / non-button tab controls in template catalogs
print("\n=== Checking Tabs and Nav Elements in Templates ===")
for tpl in sorted(tpl_dir.glob("*.js")):
    content = tpl.read_text(encoding="utf-8")
    tab_matches = re.findall(r'<(?:button|div|span|a)\b[^>]*class=["\'][^"\']*(?:tab|nav)[^"\']*["\'][^>]*>(.*?)</(?:button|div|span|a)>', content, re.DOTALL)
    for raw in tab_matches:
        w = clean_words(raw)
        if len(w) > 2:
            print(f"  [{tpl.name}] Tab > 2 words: {w} (raw: {raw[:60].strip()})")

    # Links
    links = re.findall(r'<a\b([^>]*)>(.*?)</a>', content, re.DOTALL)
    for attrs, inner in links:
        w = clean_words(inner)
        if len(w) > 2:
            print(f"  [{tpl.name}] <a> tag > 2 words: {w} (raw: {inner.strip()[:60]})")

# Check all parenthetical occurrences across all templates
print("\n=== Checking All Parentheses (.. ) in Templates & HTML ===")
all_html_files = [webapp / "index.html"] + list(tpl_dir.glob("*.js"))
for f in all_html_files:
    text = f.read_text(encoding="utf-8")
    # find parens inside tags that could be button, a, span, h2, h3, or option
    in_tags = re.findall(r'<([a-zA-Z0-9]+)\b[^>]*>(.*?)</\1>', text, re.DOTALL)
    for tag, content in in_tags:
        if tag in ("button", "a", "option", "h2", "h3", "h4", "span") and "(" in content and ")" in content:
            parens = re.findall(r'\([^\)]+\)', content)
            # check if tag is button or tab
            if tag in ("button", "a") or "tab" in content.lower() or "btn" in content.lower():
                print(f"  [{f.name}] <{tag}> has parens: {parens} (content: {content.strip()[:60]})")

print(f"\nSummary of template buttons: {total_template_buttons} buttons, {total_long_template_buttons} > 2 words, {total_bilingual_template_buttons} bilingual.")

