"""
완료 보고용 캡처 3종 (용접부 중심 타겟):
 1) home  : 홈 자세 전체
 2) path  : weld_path 오버레이 + fk(포즈)점 포개짐 (용접부 클로즈업)
 3) Trot  : 토치 T=0 vs T=90 (실물 방향 판정용)
 + basealign: 팔 정반 정합 측면
"""
import asyncio, json
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]
WC={'x':0.303,'y':1.375,'z':-0.421}  # 용접부 중심 world

async def cam(pg,phi,theta,r,tgt):
    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.orbit.tgt=o.tgt;a.updateCam();}}""",
                      {'phi':phi,'theta':theta,'r':r,'tgt':tgt})
    await pg.wait_for_timeout(900)

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) home 전체 (검증된 기본 tgt 사용)
        await pg.evaluate("(()=>{window.__dzw.setJoints({S:0,L:0,U:0,R:0,B:0,T:0});})()")
        await cam(pg,1.1,0.6,3.4,{'x':0.1,'y':0,'z':0.4})
        await pg.screenshot(path='shots/cap_home.png')
        # 2) 오버레이+fk점 포개짐, 용접부 클로즈업 (큰 초록점)
        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:0x22ff44});
          const wp=%s;
          wp.forEach(j=>{const t=a.fk(j);const s=new T.Mesh(new T.SphereGeometry(14,12,10),mat);s.position.set(t.x,t.y,t.z);grp.add(s);});
        }"""%json.dumps(arc))
        await cam(pg,0.55,0.95,2.0,WC)
        await pg.screenshot(path='shots/cap_path_overlay.png')
        await cam(pg,0.15,0.0,1.9,WC)  # 위에서 내려다본 top뷰
        await pg.screenshot(path='shots/cap_path_top.png')
        # 3) 토치 T=0 vs 90 클로즈업 (matrixWorld 갱신 후 마커 타겟)
        pose={'S':0,'L':25,'U':-25,'R':0,'B':-55,'T':0}
        async def torch_shot(tval,name):
            await pg.evaluate("(j)=>window.__dzw.setJoints(j)",{**pose,'T':tval})
            await pg.wait_for_timeout(500)
            tgt=await pg.evaluate("""()=>{const a=window.__dzw,T=a._T;a._grp.updateMatrixWorld(true);const w=new T.Vector3();a._tcpMarker.getWorldPosition(w);return {x:w.x,y:w.y,z:w.z};}""")
            await cam(pg,1.3,0.5,0.65,tgt)
            await pg.screenshot(path=f'shots/{name}.png')
        await torch_shot(0,'cap_torch_T0')
        await torch_shot(90,'cap_torch_T90')
        await torch_shot(-90,'cap_torch_Tneg90')
        # 4) 정반 정합 측면 (홈, 베이스 근처)
        await pg.evaluate("(()=>window.__dzw.setJoints({S:0,L:0,U:0,R:0,B:0,T:0}))()")
        await cam(pg,1.5,0.2,3.0,{'x':0,'y':0,'z':-0.2})
        await pg.screenshot(path='shots/cap_basealign.png')
        print("캡처 완료: cap_home cap_path_overlay cap_torch_T0/T90/Tneg90 cap_basealign")
        await br.close()
asyncio.run(main())
