"""
Verification script for explorer_remediate_2.
Simulates applying the 16 proposed drop-in replacements in-memory,
then runs Challenger 1's adversarial audit functions to confirm:
- parenthetical violations drop to 0
- word count violations remain 0
- serif violations remain 0
"""
from __future__ import annotations
import sys
import json
import re
from pathlib import Path
from bs4 import BeautifulSoup

if hasattr(sys.stdout, "reconfigure"):
    sys.stdout.reconfigure(encoding="utf-8")

PROJECT_ROOT = Path(r"c:\Projects\FreeExile")
WEBAPP_DIR = PROJECT_ROOT / "client" / "webapp"
INDEX_HTML = WEBAPP_DIR / "index.html"
TEMPLATES_DIR = WEBAPP_DIR / "js" / "ui" / "templates"
I18N_CATALOG_JS = WEBAPP_DIR / "js" / "data" / "i18n_catalog.js"

# 16 Proposed Replacements
PROPOSED_REPLACEMENTS = {
    # 1. index.html line 34
    "client/webapp/index.html": [
        (
            'data-tooltip-title="Tân Thủ Lưu Đày (Lv.1)"',
            'data-tooltip-title="Lưu Đày"'
        )
    ],
    # 2. template_catalog_activities.js line 148
    "client/webapp/js/ui/templates/template_catalog_activities.js": [
        (
            '<h3 class="text-sm font-bold text-cyan-300">Thanh Toán Web3 Crypto (Non-Custodial)</h3>',
            '<h3 class="text-sm font-bold text-cyan-300">Thanh Toán Web3</h3>'
        )
    ],
    # 3-10. template_catalog_auth.js
    "client/webapp/js/ui/templates/template_catalog_auth.js": [
        # Line 97
        (
            '<label class="block text-stone-300 font-semibold mb-1">Mật Khẩu <span class="text-rose-400">* (Tối thiểu 8 ký tự)</span></label>',
            '<label class="block text-stone-300 font-semibold mb-1">Mật Khẩu <span class="text-rose-400">*</span></label>'
        ),
        # Line 102
        (
            '<label class="block text-stone-300 font-semibold mb-1">Tên Nhân Vật / Hiệu Tự (Tùy chọn)</label>',
            '<label class="block text-stone-300 font-semibold mb-1">Tên Nhân Vật</label>'
        ),
        # Line 161
        (
            '<label class="block text-stone-300 text-xs font-semibold">Mã OTP Kích Hoạt (6 chữ số)</label>',
            '<label class="block text-stone-300 text-xs font-semibold">Mã OTP Kích Hoạt</label>'
        ),
        # Line 206
        (
            '<span class="text-xs">Ghi nhớ đăng nhập trên thiết bị (Lưu token an toàn)</span>',
            '<span class="text-xs">Ghi nhớ đăng nhập</span>'
        ),
        # Line 224
        (
            '<span>🌐</span> Đăng Nhập Bằng Tài Khoản Liên Kết (OAuth 2.0 / OIDC)',
            '<span>🌐</span> Đăng Nhập Liên Kết'
        ),
        # Line 317
        (
            '<span>⚔️</span> Danh Sách Nhân Vật (Cấp 1 & Mùa Giải)',
            '<span>⚔️</span> Danh Sách Nhân Vật'
        ),
        # Line 422
        (
            '<label class="block text-stone-300 font-semibold">Tên Nhân Vật (Hiệu Tự)</label>',
            '<label class="block text-stone-300 font-semibold">Tên Nhân Vật</label>'
        ),
        # Line 423
        (
            'placeholder="Nhập tên nhân vật (3 - 24 ký tự)"',
            'placeholder="Nhập tên nhân vật"'
        )
    ],
    # 11-14. template_catalog_inventory.js
    "client/webapp/js/ui/templates/template_catalog_inventory.js": [
        # Line 139
        (
            'title="Mở Túi Đồ Sinh Tồn (I / B)"',
            'title="Túi Đồ"'
        ),
        # Line 202
        (
            'title="Mở Đồ Đang Mặc (C)"',
            'title="Nhân Vật"'
        ),
        # Line 328
        (
            '<span class="text-stone-300">Tự động nhặt Trang Bị Cực Phẩm (Hoàng Kim):</span>',
            '<span class="text-stone-300">Tự động nhặt Trang Bị Hoàng Kim:</span>'
        ),
        # Line 474
        (
            '<span>💎</span> Ma Trận 15 Tiers Dòng Thuộc Tính (T1 - T15)',
            '<span>💎</span> Ma Trận 15 Tiers Dòng Thuộc Tính'
        )
    ],
    # 15-16. template_catalog_system.js
    "client/webapp/js/ui/templates/template_catalog_system.js": [
        # Line 324
        (
            '<span>📜</span> Lịch Sử (<span id="txt-feedback-badge-count" class="text-amber-400/90 font-mono font-bold">0</span>)',
            '<span>📜</span> Lịch Sử <span id="txt-feedback-badge-count" class="text-amber-400/90 font-mono font-bold">0</span>'
        ),
        # Line 356
        (
            '<span class="text-[10px] text-stone-500 font-normal">(Tối thiểu 10 ký tự)</span>',
            '<span class="text-[10px] text-stone-500 font-normal">Tối thiểu 10 ký tự</span>'
        )
    ]
}

def get_modified_content(rel_path: str) -> str:
    path = PROJECT_ROOT / rel_path
    content = path.read_text(encoding="utf-8")
    if rel_path in PROPOSED_REPLACEMENTS:
        for old, new in PROPOSED_REPLACEMENTS[rel_path]:
            if old not in content:
                raise ValueError(f"Old target string not found in {rel_path}:\n{old}")
            content = content.replace(old, new, 1)
    return content

def extract_templates_from_code(content: str):
    matches = re.finditer(r"reg\s*\(\s*['\"]([^'\"]+)['\"]\s*,\s*([`'\"])(.*?)\2\s*\)", content, re.DOTALL)
    for m in matches:
        yield m.group(1), m.group(3)

def run_adversarial_check():
    print("Testing In-Memory Modified Code Against Challenger 1 Rules...")
    violations = []
    
    # 1. Check index.html
    index_content = get_modified_content("client/webapp/index.html")
    soup_html = BeautifulSoup(index_content, "html.parser")
    for el in soup_html.find_all(["h1", "h2", "h3", "h4", "h5", "h6", "label", "button", "a"]):
        text = el.get_text(strip=True)
        if "(" in text or ")" in text:
            violations.append({"source": "index.html", "el": str(el), "text": text})
    for el in soup_html.find_all(True):
        for attr in ["data-tooltip-title", "title", "aria-label", "placeholder"]:
            val = el.get(attr)
            if val and ("(" in val or ")" in val):
                violations.append({"source": "index.html attr", "el": str(el), "val": val})

    # 2. Check templates
    for tf in sorted(TEMPLATES_DIR.glob("*.js")):
        rel = f"client/webapp/js/ui/templates/{tf.name}"
        code = get_modified_content(rel)
        for tid, tpl_html in extract_templates_from_code(code):
            tsoup = BeautifulSoup(tpl_html, "html.parser")
            for el in tsoup.find_all(["h1", "h2", "h3", "h4", "h5", "h6", "label", "button", "a"]):
                text = el.get_text(strip=True)
                if "(" in text or ")" in text:
                    violations.append({"source": f"{tf.name} [{tid}]", "el": str(el)[:80], "text": text})
            for el in tsoup.find_all(True):
                for attr in ["data-tooltip-title", "title", "aria-label", "placeholder"]:
                    val = el.get(attr)
                    if val and ("(" in val or ")" in val):
                        violations.append({"source": f"{tf.name} [{tid}] attr", "el": str(el)[:80], "val": val})

    print(f"Total Remaining Parenthetical Violations: {len(violations)}")
    if violations:
        for v in violations:
            print("  VIOLATION:", v)
    else:
        print("SUCCESS! Zero parenthetical violations remain in headings, labels, buttons, or target attributes!")

    # Check interactive controls word count
    from adversarial_ui_stress_test import extract_words
    wc_violations = []
    # 1. index.html interactive
    for el in soup_html.find_all(lambda e: e.name in ["button", "a", "input"] or e.get("role") in ["button", "tab"] or any("tab" in c for c in e.get("class", []))):
        if el.name == "input" and el.get("type", "text") not in ["button", "submit", "reset"]:
            continue
        txt = el.get_text(separator=" ", strip=True)
        w = extract_words(txt)
        if len(w) > 2:
            wc_violations.append({"source": "index.html", "el": str(el)[:80], "words": w})
    # 2. templates interactive
    for tf in sorted(TEMPLATES_DIR.glob("*.js")):
        rel = f"client/webapp/js/ui/templates/{tf.name}"
        code = get_modified_content(rel)
        for tid, tpl_html in extract_templates_from_code(code):
            tsoup = BeautifulSoup(tpl_html, "html.parser")
            for el in tsoup.find_all(lambda e: e.name in ["button", "a", "input"] or e.get("role") in ["button", "tab"] or any("tab" in c for c in e.get("class", []))):
                if el.name == "input" and el.get("type", "text") not in ["button", "submit", "reset"]:
                    continue
                txt = el.get_text(separator=" ", strip=True)
                w = extract_words(txt)
                if len(w) > 2:
                    wc_violations.append({"source": f"{tf.name} [{tid}]", "el": str(el)[:80], "words": w})

    print(f"Total Remaining Interactive Word Count Violations: {len(wc_violations)}")
    if wc_violations:
        for w in wc_violations:
            print("  WC VIOLATION:", w)
    else:
        print("SUCCESS! Zero interactive word count violations remain!")

if __name__ == "__main__":
    # Add challenger_streamline_1 to sys.path
    sys.path.insert(0, str(PROJECT_ROOT / ".agents" / "teamwork" / "challenger_streamline_1"))
    run_adversarial_check()

