"""완료#3: 재로드2회+자세변경 후 토치끝 구 재출현 여부 / JBI 홈위치 조회(=CEO 홈 비교)."""
import asyncio, json
from playwright.async_api import async_playwright
URL='http://localhost:8090/DOZIKWORKS_OS_v5_locked.dc.html'
CEO_HOME={"S":-0.7,"L":-59.4,"U":-44.4,"R":-1.0,"B":-92.9,"T":-1.1}
async def count_spheres(pg):
    return await pg.evaluate("""()=>{ const d=window.__dzw,T=d._T; const tt=d._truthTool; tt.updateMatrixWorld(true);
      const tcp=new T.Vector3(d.tcpOffset[0],d.tcpOffset[1],d.tcpOffset[2]); let vis=[];
      tt.traverse(o=>{ if(o.isMesh&&o.geometry&&o.geometry.type==='SphereGeometry'&&o.visible){ if(o.position.distanceTo(tcp)<40) vis.push(o.name||'sphere'); }});
      return vis; }""")
async def main():
    async with async_playwright() as p:
        br=await p.chromium.launch(channel='msedge',headless=True)
        # 1차 로드
        pg=await br.new_page(viewport={'width':1200,'height':800})
        await pg.goto(URL); await pg.wait_for_function("window.__dzw && window.__dzw._torchMesh",timeout=15000)
        # JBI 홈 조회
        home=await pg.evaluate("""()=>{ const d=window.__dzw; const out={};
          out.anchors0 = (d.DZW5&&d.DZW5.anchors)?null:null;
          try{ out.anchor0 = window.DZW5? window.DZW5.anchors[0] : (d.anchors?d.anchors[0]:null); }catch(e){ out.anchor0=null; }
          // gotoStep(0) 후 관절 = JBI 홈
          if(d.gotoStep) d.gotoStep(0);
          const j=d.state.joints; out.jbiHome={S:+j.S.toFixed(2),L:+j.L.toFixed(2),U:+j.U.toFixed(2),R:+j.R.toFixed(2),B:+j.B.toFixed(2),T:+j.T.toFixed(2)};
          // jbi stepPoses[0] 원본(있으면)
          try{ out.stepPose0 = d.jbi? d.jbi.stepPoses[0] : null; }catch(e){ out.stepPose0=null; }
          return out; }""")
        # 자세 변경 후 구
        await pg.evaluate("()=>{ const d=window.__dzw; if(d.setJoints) d.setJoints({S:20,L:-30,U:-20,R:10,B:-60,T:15}); }")
        await pg.wait_for_timeout(300)
        s1=await count_spheres(pg)
        await pg.close()
        # 2차 로드(새로고침)
        pg2=await br.new_page(viewport={'width':1200,'height':800})
        await pg2.goto(URL); await pg2.wait_for_function("window.__dzw && window.__dzw._torchMesh",timeout=15000)
        await pg2.evaluate("()=>{ const d=window.__dzw; if(d.setJoints) d.setJoints({S:-40,L:-70,U:-10,R:-20,B:-100,T:-30}); }")
        await pg2.wait_for_timeout(300)
        s2=await count_spheres(pg2)
        print("JBI홈/앵커:", json.dumps(home,ensure_ascii=False))
        print("CEO홈:", CEO_HOME)
        print("자세변경#1 토치끝 가시구:", s1)
        print("재로드+자세변경#2 토치끝 가시구:", s2)
        await br.close()
asyncio.run(main())
