import asyncio, json
from playwright.async_api import async_playwright

async def run():
    async with async_playwright() as p:
        br = await p.chromium.launch(headless=False, args=['--window-size=1400,900'])
        pg = await br.new_page(viewport={'width':1400,'height':900})

        errors = []
        pg.on('console', lambda m: print(f'[{m.type}] {m.text}') if m.type in ('error','warning') else None)
        pg.on('pageerror', lambda e: errors.append(str(e)))

        await pg.goto('http://localhost:8090/DOZIKWORKS_OS_v5_locked.dc.html')
        await pg.wait_for_timeout(50000)

        # 상태 확인
        state = await pg.evaluate('''() => {
            const app = window.__dzw;
            const btn = document.getElementById('dzw-edge-mode-btn');
            return {
                appExists: !!app,
                knuckleMesh: !!app?._knuckleMesh,
                faceMode: app?._faceMode,
                btnExists: !!btn,
                btnOnclick: !!btn?.onclick,
                xformPanel: document.getElementById('dzw-xform-panel')?.style?.display
            };
        }''')
        print('초기 상태:', json.dumps(state, indent=2))

        # 너클 클릭해서 패널 열기
        rect = await pg.evaluate('() => { const r=window.__dzw?.three?.rnd?.domElement?.getBoundingClientRect(); return r?{l:r.left,t:r.top,w:r.width,h:r.height}:null; }')
        if rect:
            L,T,W,H = rect['l'],rect['t'],rect['w'],rect['h']
            # 너클 히트 좌표 찾기
            hit = await pg.evaluate(f'''() => {{
                const app=window.__dzw, cam=app.three.cam, mesh=app._knuckleMesh;
                for(let cy=50;cy<{H}-50;cy+=20)for(let cx=50;cx<{W}-50;cx+=20){{
                    app._ray.setFromCamera({{x:(cx/{W})*2-1,y:-(cy/{H})*2+1}},cam);
                    const h=app._ray.intersectObjects([mesh],true);
                    if(h.length) return {{px:Math.round({L}+cx),py:Math.round({T}+cy)}};
                }}
                return null;
            }}''')
            print('너클 좌표:', hit)

            if hit:
                # 너클 클릭 → 패널 열기
                await pg.mouse.click(hit['px'], hit['py'])
                await pg.wait_for_timeout(500)

                state2 = await pg.evaluate('''() => {
                    const btn=document.getElementById('dzw-edge-mode-btn');
                    return {
                        xformPanel: document.getElementById('dzw-xform-panel')?.style?.display,
                        btnOnclick: !!btn?.onclick,
                        btnText: btn?.textContent
                    };
                }''')
                print('패널 열기 후:', json.dumps(state2, indent=2))

                # 버튼 JS onclick 직접 호출
                r = await pg.evaluate('''() => {
                    const btn=document.getElementById('dzw-edge-mode-btn');
                    if(!btn) return 'btn없음';
                    if(!btn.onclick) return 'onclick없음';
                    btn.onclick();
                    return 'mode=' + window.__dzw._faceMode;
                }''')
                print('버튼 클릭 결과:', r)

        if errors:
            print('페이지 에러:', errors)

        await br.close()

asyncio.run(run())
