"""
신규 토치 검증:
 - 토치 노즐끝(메시 로컬원점) 월드좌표가 TCP마커와 포개지는가 (수치)
 - 캡처 4장: 홈 / T0 / T90 / 용접자세 클로즈업
"""
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 cam(pg,phi,theta,r):
    await pg.evaluate("(o)=>{const a=window.__dzw;if(a.orbit){a.orbit.phi=o.phi;a.orbit.theta=o.theta;a.orbit.r=o.r;a.updateCam();}}",{'phi':phi,'theta':theta,'r':r})
    await pg.wait_for_timeout(800)
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})
        logs=[]; pg.on('console',lambda m: logs.append(m.text))
        await pg.goto(URL); await pg.wait_for_timeout(33000)
        # 토치 로드 로그
        for t in logs:
            if '[torch]' in t: print("콘솔:", t)
        # 노즐끝(토치 메시 로컬원점) vs 마커 월드좌표 (4자세)
        idxs=[0,34,63,99]
        for ti,idx in enumerate(idxs):
            j=arc[idx]
            res=await pg.evaluate("""async (j)=>{const a=window.__dzw,T=a._T;
              a.setJoints(j); await new Promise(r=>setTimeout(r,150)); a._grp.updateMatrixWorld(true);
              const torch=a._torchNode.children.find(c=>c.name==='torch_TCP540');
              const tipW=new T.Vector3(); torch.getWorldPosition(tipW);  // 메시 원점=노즐끝
              const mkW=new T.Vector3(); a._tcpMarker.getWorldPosition(mkW);
              const d=tipW.distanceTo(mkW)*1000; // m→mm
              return d;
            }""",j)
            print(f"  자세{ti+1}(idx{idx}): 노즐끝↔마커 = {res:.2f}mm", "✅" if res<2 else "❌")
        # 캡처
        await pg.evaluate("""async ()=>{const a=window.__dzw; a.loadWeldPath(); await new Promise(r=>setTimeout(r,1500)); a.setJoints({S:0,L:0,U:0,R:0,B:0,T:0});}""")
        await cam(pg,1.1,0.6,3.2); await pg.screenshot(path='shots/TORCH_home.png')
        base={'S':0,'L':30,'U':-30,'R':0,'B':-50}
        await pg.evaluate("(j)=>window.__dzw.setJoints(j)",{**base,'T':0}); await cam(pg,1.25,0.35,1.4); await pg.screenshot(path='shots/TORCH_T0.png')
        await pg.evaluate("(j)=>window.__dzw.setJoints(j)",{**base,'T':90}); await pg.wait_for_timeout(600); await pg.screenshot(path='shots/TORCH_T90.png')
        await pg.evaluate("(j)=>window.__dzw.setJoints(j)",arc[0]); await cam(pg,1.15,0.5,1.5); await pg.screenshot(path='shots/TORCH_weld.png')
        print("캡처: TORCH_home TORCH_T0 TORCH_T90 TORCH_weld")
        await br.close()
asyncio.run(main())
