# dzw_pick_toolbar.js 검증 — 페이지 로드 콘솔에러 + 사이드바/팔레트 버튼 전수 클릭 시뮬레이션
# 참고: _torch_unlock.flag / dxf_*.json 404는 기존 폴링(이번 작업 무관) → 별도 집계
import asyncio, json
from playwright.async_api import async_playwright

CLICK_ORDER = [
    'select','move','rotate','zoom','frame',
    'jog','jog','tcp','tcp',
    'toolbase','collisionCheck',
    'pointAdd','pointEdit','pointDelete','homeSet','arcOn','arcOff',
    'measDist','measAngle','measTcp',
    'markPoint','toggleMarkerPanel','toggleMarkerPanel',
    'toggleOpacityTool','toggleOpacityTool',
    'toggleJbiPicker','toggleJbiPicker',
    'sysSettings','sysIo','sysIo','sysLog',
    'select',
]

def is_noise(t):
    return 'Failed to load resource' in t  # 기존 404 폴링 노이즈

async def main():
    errors, noise = [], []
    async with async_playwright() as p:
        br = await p.chromium.launch(headless=True)
        pg = await br.new_page()
        await pg.set_viewport_size({'width':1400,'height':900})
        def on_console(m):
            if m.type=='error':
                (noise if is_noise(m.text) else errors).append('[console.error] '+m.text)
        pg.on('console', on_console)
        pg.on('pageerror', lambda e: errors.append('[pageerror] '+str(e)))
        await pg.goto('http://localhost:8090/DOZIKWORKS_OS_v5_locked.dc.html')
        await pg.wait_for_timeout(16000)
        print('=== 로드 완료. 실질 콘솔에러:', len(errors), '/ 기존 404 노이즈:', len(noise))
        for e in errors: print('  ', e[:200])

        wired = await pg.evaluate("""() => {
            const out={};
            document.querySelectorAll('[data-dzw-pick]').forEach(el=>{
                const id=el.getAttribute('data-dzw-pick'); out[id]=(out[id]||0)+1; });
            return out; }""")
        print('=== 배선된 버튼:', json.dumps(wired, ensure_ascii=False))

        results, fails = {}, 0
        for tid in CLICK_ORDER:
            before = len(errors)
            ok = await pg.evaluate("""(tid) => {
                const el=document.querySelector('[data-dzw-pick="'+tid+'"]');
                if(!el) return false; el.click(); return true; }""", tid)
            await pg.wait_for_timeout(400)
            new_err = errors[before:]
            results.setdefault(tid, []).append('없음' if not ok else ('에러:'+';'.join(new_err)[:150] if new_err else 'OK'))
        print('=== 사이드바 클릭 결과 ===')
        for tid, rr in results.items():
            s = ','.join(rr)
            if '에러' in s or '없음' in s: fails += 1
            print(f'  {tid}: {s}')

        # ── 팔레트 (큰 화면 모드) ──
        opened = await pg.evaluate("()=>{const a=window.__dzw; if(a&&a.openFull){a.openFull();return true;} return false;}")
        await pg.wait_for_timeout(2500)  # 재스캔 주기 대기
        pal = await pg.evaluate("""()=>{
            const p=document.getElementById('dzw-toolbar-panel');
            if(!p) return null;
            return [...p.querySelectorAll('[data-dzw-pick]')].map(e=>e.getAttribute('data-dzw-pick')); }""")
        print('=== 큰화면 진입:', opened, '/ 팔레트 배선:', json.dumps(pal, ensure_ascii=False))
        pal_fail = 0
        if pal:
            for tid in pal:
                before = len(errors)
                await pg.evaluate("""(tid)=>{
                    const p=document.getElementById('dzw-toolbar-panel');
                    const el=p&&p.querySelector('[data-dzw-pick="'+tid+'"]'); if(el) el.click(); }""", tid)
                await pg.wait_for_timeout(300)
                ne = errors[before:]
                if ne: pal_fail += 1; print(f'  팔레트 {tid}: 에러 {";".join(ne)[:120]}')
            print(f'=== 팔레트 {len(pal)}개 클릭 — 에러 버튼 {pal_fail}개')
        print('=== 최종: 실질 콘솔에러', len(errors), '/ 사이드바 실패', fails, '/ 팔레트 실패', pal_fail)
        await pg.screenshot(path='../pick_toolbar_verify.png')
        await br.close()

asyncio.run(main())
