import asyncio, os
from playwright.async_api import async_playwright

OUT = r'E:\도진팩토리\3D스캔및티칭시스템\shots'

async def main():
    async with async_playwright() as p:
        br = await p.chromium.launch(headless=False, args=['--window-size=1536,864'])
        pg = await br.new_page(viewport={'width':1536,'height':864})
        pg.on('console', lambda m: print(f'[{m.type}] {m.text}') if m.type in ('error','warn','log') else None)

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

        # 너클붐 선택 → 패널 열기
        await pg.evaluate('() => window.__dzw && window.__dzw._knuckleSelect && window.__dzw._knuckleSelect()')
        await pg.wait_for_timeout(500)

        # 버튼 찾기
        info = await pg.evaluate('''() => {
            // onclick으로 찾기
            const all = document.querySelectorAll('button, div[onclick]');
            const results = [];
            for(const el of all){
                const txt = el.textContent.trim();
                if(txt.includes('구간 용접') || txt.includes('티칭하기')){
                    const r = el.getBoundingClientRect();
                    results.push({
                        tag: el.tagName,
                        text: txt.slice(0,30),
                        display: window.getComputedStyle(el).display,
                        visibility: window.getComputedStyle(el).visibility,
                        pointerEvents: window.getComputedStyle(el).pointerEvents,
                        inViewport: r.width>0 && r.height>0,
                        rect: {top:Math.round(r.top), left:Math.round(r.left),
                               bottom:Math.round(r.bottom), right:Math.round(r.right),
                               w:Math.round(r.width), h:Math.round(r.height)},
                        panelDisplay: document.getElementById('dzw-xform-panel')?.style?.display,
                        bodyScrollable: document.getElementById('dzw-xform-body')?.scrollHeight,
                    });
                }
            }
            return results;
        }''')
        print(f'[버튼 검색 결과] {info}')

        # 패널 스크롤 상태
        scroll = await pg.evaluate('''() => {
            const body = document.getElementById('dzw-xform-body');
            if(!body) return {err:'body없음'};
            return {scrollTop:body.scrollTop, scrollHeight:body.scrollHeight, clientHeight:body.clientHeight};
        }''')
        print(f'[패널 스크롤] {scroll}')

        # 스크린샷
        await pg.screenshot(path=os.path.join(OUT,'btn_check.png'))
        print('[스샷] btn_check.png')

        # 패널 스크롤 끝까지 내리기
        await pg.evaluate('''() => {
            const body = document.getElementById('dzw-xform-body');
            if(body) body.scrollTop = body.scrollHeight;
        }''')
        await pg.wait_for_timeout(300)
        await pg.screenshot(path=os.path.join(OUT,'btn_check_scrolled.png'))
        print('[스샷] btn_check_scrolled.png')

        # 버튼 직접 JS로 클릭
        clicked = await pg.evaluate('''() => {
            const all = document.querySelectorAll('button');
            for(const b of all){
                if(b.textContent.includes('구간 용접 티칭하기')){
                    b.click();
                    return {clicked:true, text:b.textContent.trim()};
                }
            }
            return {clicked:false};
        }''')
        print(f'[JS 클릭] {clicked}')
        await pg.wait_for_timeout(300)
        mode = await pg.evaluate('() => !!window.__dzw._hoverTeachMode')
        print(f'[hoverTeachMode] {mode}')

        await pg.wait_for_timeout(1000)
        await br.close()

asyncio.run(main())
