"""와이어끝 용접점 검증: 빨강구=TCP+15(공구Z), fkWire=fk+15, 티칭=와이어끝. 캡처 2장."""
import asyncio, json, math
from playwright.async_api import async_playwright
URL='http://localhost:8090/DOZIKWORKS_OS_v5_locked.dc.html'
wp=json.loads(open(r'E:\도진팩토리\3D스캔및티칭시스템\weld_path.json',encoding='utf-8').read())
arc=[{k:p[k] for k in ['S','L','U','R','B','T']} for p in wp['poses'] if p.get('arc')==1]
async def main():
    async with async_playwright() as p:
        br=await p.chromium.launch(channel='msedge',headless=True)
        pg=await br.new_page(viewport={'width':1536,'height':864})
        await pg.goto(URL); await pg.wait_for_timeout(33000)
        idxs=[0,34,63,99]
        for k,idx in enumerate(idxs):
            r=await pg.evaluate("""(j)=>{const a=window.__dzw,T=a._T; a.setJoints(j); a._grp.updateMatrixWorld(true);
              const wp=new T.Vector3(); a._weldPoint.getWorldPosition(wp);
              const mk=new T.Vector3(); a._tcpMarker.getWorldPosition(mk);
              const fkNoz=a.fk(j), fkWire=a.fkWire(j);
              const d_fk=Math.hypot(fkWire.x-fkNoz.x,fkWire.y-fkNoz.y,fkWire.z-fkNoz.z);
              // 빨강구 월드(mm, _grp로컬) vs fkWire
              const wl=a._grp.worldToLocal(wp.clone());
              const dWtoFk=Math.hypot(wl.x-fkWire.x,wl.y-fkWire.y,wl.z-fkWire.z);
              return {red_vs_mk:wp.distanceTo(mk)*1000, fkWire_minus_fk:d_fk, red_vs_fkWire_mm:dWtoFk,
                      orangeVis:a._tcpMarker.visible, redVis:a._weldPoint.visible};
            }""",arc[idx])
            print(f" 자세{k+1}: 빨강구↔노즐TCP={r['red_vs_mk']:.1f}mm  fkWire-fk={r['fkWire_minus_fk']:.1f}mm  빨강구↔fkWire={r['red_vs_fkWire_mm']:.2f}mm")
        print(f" 주황(노즐마커) visible={r['orangeVis']} (False=삭제됨) / 빨강(용접점) visible={r['redVis']}")
        # 캡처: 용접점 클로즈업 + 전체
        pose={'S':0,'L':30,'U':-30,'R':0,'B':-50,'T':0}
        tgt=await pg.evaluate("""(j)=>{const a=window.__dzw,T=a._T; a.setJoints(j); a._grp.updateMatrixWorld(true);
          const w=new T.Vector3(); a._weldPoint.getWorldPosition(w); return {x:w.x,y:w.y,z:w.z};}""",pose)
        await pg.evaluate("""(o)=>{const a=window.__dzw; a.orbit.tgt.set(o.x,o.y,o.z);a.orbit.r=0.7;a.orbit.phi=1.25;a.orbit.theta=0.55;a.updateCam();}""",tgt)
        await pg.wait_for_timeout(900); await pg.screenshot(path='shots/WIRE_close.png')
        await pg.evaluate("""()=>{const a=window.__dzw; a.setJoints(a.__q||{S:0,L:0,U:0,R:0,B:0,T:0}); a.orbit.tgt.set(0.1,0,0.4);a.orbit.r=3.2;a.orbit.phi=1.1;a.orbit.theta=0.6;a.updateCam();}""")
        await pg.wait_for_timeout(900); await pg.screenshot(path='shots/WIRE_full.png')
        print("캡처: WIRE_close.png WIRE_full.png")
        await br.close()
asyncio.run(main())
