"""
1) PLAY 스팟체크: 재생 중 마커가 관절과 함께 움직이는가 (토치 정지 아님)
2) 경로 포개짐 깔끔한 top뷰 (tgt 미설정)
"""
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})
        await pg.goto(URL); await pg.wait_for_timeout(32000)
        # 1) PLAY 스팟체크 — 재생 시작, 두 시점에서 마커world+관절 읽기
        async def snap():
            return await pg.evaluate("""()=>{const a=window.__dzw,T=a._T;a._grp.updateMatrixWorld(true);
              const w=new T.Vector3();a._tcpMarker.getWorldPosition(w);
              return {pos:a.state.pos, T:a.state.joints.T, mk:[w.x,w.y,w.z]};}""")
        await pg.evaluate("(()=>{const a=window.__dzw; a.setState({playing:true,speed:8});})()")
        await pg.wait_for_timeout(1500); s1=await snap()
        await pg.wait_for_timeout(1800); s2=await snap()
        await pg.evaluate("(()=>window.__dzw.setState({playing:false}))()")
        d=math.sqrt(sum((a-b)**2 for a,b in zip(s1['mk'],s2['mk'])))
        print(f"PLAY 스팟: t1 pos={s1['pos']:.1f} 마커={[round(x,3) for x in s1['mk']]}")
        print(f"          t2 pos={s2['pos']:.1f} 마커={[round(x,3) for x in s2['mk']]}")
        print(f"  마커 이동거리 {d*1000:.0f}mm →", "재생 중 토치 추종 ✅" if d*1000>5 else "토치 정지 의심 ❌")
        # 2) 오버레이+큰 fk점 주입 후 top뷰 (tgt 미설정)
        await pg.evaluate("""async ()=>{const a=window.__dzw,T=a._T,grp=a._grp;
          a.loadWeldPath(); await new Promise(r=>setTimeout(r,2200));
          const mat=new T.MeshBasicMaterial({color:0x00ff55});
          const wp=%s;
          wp.forEach(j=>{const t=a.fk(j);const s=new T.Mesh(new T.SphereGeometry(11,12,10),mat);s.position.set(t.x,t.y,t.z);grp.add(s);});
          a.setJoints({S:0,L:0,U:0,R:0,B:0,T:0});
        }"""%json.dumps(arc))
        for tag,(phi,theta,r) in {'A':(0.22,0.5,3.4),'B':(0.35,0.75,2.9),'C':(0.15,1.05,3.1)}.items():
            await cam(pg,phi,theta,r); await pg.screenshot(path=f'shots/PATH_{tag}.png')
        print("경로 캡처: PATH_A PATH_B PATH_C")
        await br.close()
asyncio.run(main())
