"""
BUILD #11 — 호버티칭 검증
1. 페이지 로드 + 배너 확인
2. 너클붐 선택 + 패널 열기
3. "구간 용접 티칭하기" 버튼 클릭 → _hoverTeachMode=true 확인
4. 캔버스 표면 5점 시뮬 클릭 (pointerdown button=0)
5. 우클릭 → 점 1개 삭제 확인
6. "구간 완료" 버튼 → _teachSegments 1개 확인
7. 스크린샷 저장
"""
import asyncio, os
from playwright.async_api import async_playwright

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

async def shot(pg, name):
    path = os.path.join(OUT, name)
    await pg.screenshot(path=path, full_page=False)
    print(f'  [스샷] {name}')

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})
        errs = []
        pg.on('pageerror', lambda e: errs.append(str(e)))
        pg.on('console', lambda m: print(f'  [{m.type}] {m.text}') if m.type in ('error','warn','log') else None)

        print('=== 1: 페이지 로드 ===')
        await pg.goto('http://localhost:8090/DOZIKWORKS_OS_v5_locked.dc.html')
        await pg.wait_for_timeout(4000)
        banner = await pg.evaluate('() => document.getElementById("dzw-build-banner")?.textContent || "없음"')
        print(f'  배너: {banner}')
        await shot(pg, 't11_01_load.png')

        if 'BUILD #11' not in banner:
            print(f'  ⚠️ BUILD #11 배너 없음: {banner}')
            await br.close(); return

        print('\n=== 2: 너클붐 선택 + 패널 ===')
        state = await pg.evaluate('''() => {
            const app = window.__dzw;
            if(!app||!app._knuckleMesh) return {err:'앱/메시없음'};
            app._knuckleSelect();
            return {panel: document.getElementById('dzw-xform-panel')?.style?.display};
        }''')
        print(f'  패널: {state}')
        await pg.wait_for_timeout(500)
        await shot(pg, 't11_02_panel.png')

        print('\n=== 3: 구간 티칭 버튼 ===')
        # 패널 스크롤 필요할 수 있어 직접 JS 호출
        mode_before = await pg.evaluate('() => !!window.__dzw._hoverTeachMode')
        await pg.evaluate('() => DZW5_EDGEPATH.startTeachSegment(window.__dzw)')
        await pg.wait_for_timeout(300)
        mode_after = await pg.evaluate('() => !!window.__dzw._hoverTeachMode')
        print(f'  _hoverTeachMode: {mode_before} → {mode_after}')
        await shot(pg, 't11_03_teach_on.png')

        if not mode_after:
            print('  ⚠️ _hoverTeachMode가 true가 아님')
            await br.close(); return

        print('\n=== 4: 캔버스 표면 5점 실제 클릭 ===')
        # 캔버스 크기 가져오기
        canvas_rect = await pg.evaluate('''() => {
            const c = document.querySelector('canvas');
            const r = c.getBoundingClientRect();
            return {left:r.left,top:r.top,width:r.width,height:r.height};
        }''')
        cx = canvas_rect['left'] + canvas_rect['width']/2
        cy = canvas_rect['top'] + canvas_rect['height']/2
        # 캔버스 중앙 근처 5곳 클릭
        click_pts = [
            (cx, cy), (cx-80, cy-60), (cx+80, cy-60),
            (cx-80, cy+60), (cx+80, cy+60)
        ]
        for px, py in click_pts:
            await pg.mouse.click(px, py, button='left')
            await pg.wait_for_timeout(200)
        pts_count = await pg.evaluate('() => window.__dzw._currentSegmentPts?.length || 0')
        print(f'  찍힌 점: {pts_count}개 (표면 히트 수)')
        await pg.wait_for_timeout(500)
        await shot(pg, 't11_04_points.png')

        print('\n=== 5: 우클릭 → 직전점 삭제 ===')
        pts_before = await pg.evaluate('() => window.__dzw._currentSegmentPts?.length || 0')
        # 우클릭 시뮬
        await pg.mouse.click(cx, cy, button='right')
        await pg.wait_for_timeout(300)
        pts_after = await pg.evaluate('() => window.__dzw._currentSegmentPts?.length || 0')
        print(f'  점 수: {pts_before} → {pts_after} (삭제={pts_before-pts_after}개)')
        await shot(pg, 't11_05_pop.png')

        if pts_before > 0 and pts_before - pts_after != 1:
            print(f'  ⚠️ 직전점 삭제가 1개가 아님 (삭제={pts_before-pts_after})')
        elif pts_before == 0:
            print(f'  ⚠️ 점이 없어 삭제 테스트 불가 (표면 클릭이 안 닿은 듯)')

        print('\n=== 6: 구간 완료 (점 3개 다시 찍고 완료) ===')
        # 우클릭으로 삭제 후 점이 0개라서 다시 3개 찍기
        for px2, py2 in [(cx-60,cy),(cx,cy),(cx+60,cy)]:
            await pg.mouse.click(px2, py2, button='left')
            await pg.wait_for_timeout(200)
        await pg.wait_for_timeout(300)
        await pg.evaluate('() => DZW5_EDGEPATH.finishTeachSegment(window.__dzw)')
        await pg.wait_for_timeout(500)
        segs = await pg.evaluate('() => window.__dzw._teachSegments?.length || 0')
        cur_pts = await pg.evaluate('() => window.__dzw._currentSegmentPts?.length || 0')
        print(f'  확정구간: {segs}개, 현재구간초기화: {cur_pts}점')
        await shot(pg, 't11_06_finish.png')

        if errs: print(f'\n⚠️ 페이지 에러: {errs}')

        print('\n=== 결과 ===')
        ok = mode_after and segs>=1
        print('✅ 1단계 검증 성공!' if ok else '❌ 일부 실패 — 위 항목 확인')
        print(f'shots 폴더: {OUT}')
        await pg.wait_for_timeout(2000)
        await br.close()

asyncio.run(main())
