"""
호버 디버그 v2 — 너클붐 실제 위치 찾아서 그 위에서 pointermove
"""
import asyncio, os
from playwright.async_api import async_playwright

OUT = r'E:\도진팩토리\3D스캔및티칭시스템\shots'
os.makedirs(OUT, exist_ok=True)

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})
        logs = []
        pg.on('console', lambda m: logs.append(f'[{m.type}] {m.text}'))

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

        # 너클붐 선택 + 티칭 ON
        await pg.evaluate('() => { window.__dzw._knuckleSelect&&window.__dzw._knuckleSelect(); }')
        await pg.wait_for_timeout(500)
        await pg.evaluate('() => DZW5_EDGEPATH.startTeachSegment(window.__dzw)')
        await pg.wait_for_timeout(300)

        # 너클붐이 화면 어디에 투영되는지 찾기 (grid scan)
        hit_info = await pg.evaluate('''() => {
            const app = window.__dzw;
            const mesh = app._knuckleMesh;
            const cam = app.three && app.three.cam;
            if(!mesh||!cam) return {err:'없음'};
            cam.updateMatrixWorld();
            const canvas = document.querySelector('canvas');
            const r = canvas.getBoundingClientRect();
            let hits = [];
            for(let py=r.top+20; py<r.bottom-20; py+=30){
              for(let px=r.left+20; px<r.right-20; px+=40){
                const mx=((px-r.left)/r.width)*2-1;
                const my=-((py-r.top)/r.height)*2+1;
                app._ray.setFromCamera({x:mx,y:my}, cam);
                const h=app._ray.intersectObjects([mesh],true);
                if(h.length) hits.push({px:Math.round(px),py:Math.round(py),mx:mx.toFixed(2),my:my.toFixed(2)});
              }
            }
            return {count:hits.length, first:hits[0]||null, last:hits[hits.length-1]||null};
        }''')
        print(f'[너클붐 스캔] 히트 {hit_info}')

        if not hit_info.get('first'):
            print('  ⚠️ 너클붐 화면에 없음 — FIT 클릭 후 재시도')
            # FIT 버튼 클릭
            fit = await pg.evaluate('''() => {
                const btns = document.querySelectorAll('button,div[onclick]');
                for(const b of btns) if(b.textContent.trim()==='FIT') { b.click(); return true; }
                return false;
            }''')
            print(f'  FIT 클릭: {fit}')
            await pg.wait_for_timeout(1000)

            hit_info = await pg.evaluate('''() => {
                const app=window.__dzw; const mesh=app._knuckleMesh; const cam=app.three&&app.three.cam;
                if(!mesh||!cam) return {err:'없음'};
                cam.updateMatrixWorld();
                const canvas=document.querySelector('canvas');
                const r=canvas.getBoundingClientRect();
                let hits=[];
                for(let py=r.top+20;py<r.bottom-20;py+=30)
                  for(let px=r.left+20;px<r.right-20;px+=40){
                    const mx=((px-r.left)/r.width)*2-1, my=-((py-r.top)/r.height)*2+1;
                    app._ray.setFromCamera({x:mx,y:my},cam);
                    const h=app._ray.intersectObjects([mesh],true);
                    if(h.length) hits.push({px:Math.round(px),py:Math.round(py)});
                  }
                return {count:hits.length, first:hits[0]||null};
            }''')
            print(f'[FIT 후 스캔] {hit_info}')

        # 너클붐 위에서 실제 마우스 이동
        first = hit_info.get('first')
        if first:
            px, py = first['px'], first['py']
            print(f'\n[너클붐 위에서 pointermove] ({px},{py})')
            logs.clear()
            for dx in range(-50, 51, 10):
                await pg.mouse.move(px+dx, py)
                await pg.wait_for_timeout(30)
            await pg.wait_for_timeout(500)

            hover = await pg.evaluate('''() => {
                const dot=window.__dzw._hoverDot;
                if(!dot) return {exists:false};
                return {exists:true, visible:dot.visible,
                    x:dot.position.x.toFixed(1), y:dot.position.y.toFixed(1), z:dot.position.z.toFixed(1)};
            }''')
            print(f'[호버닷] {hover}')

            # 좌클릭 테스트
            await pg.mouse.click(px, py, button='left')
            await pg.wait_for_timeout(300)
            pts = await pg.evaluate('() => window.__dzw._currentSegmentPts?.length||0')
            print(f'[좌클릭 후 점 수] {pts}개')

        path = os.path.join(OUT, 'hover_debug2.png')
        await pg.screenshot(path=path)
        print(f'\n[스샷] hover_debug2.png')

        if logs:
            print('\n[콘솔]')
            for l in logs: print(' ', l)

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

asyncio.run(main())
