"""토치 지오메트리 분석: 중심축 따라 반경 프로파일 → 플랜지 원판/목 경계(자를 면) 산출."""
import asyncio, json
from playwright.async_api import async_playwright
URL='http://localhost:8090/DOZIKWORKS_OS_v5_locked.dc.html'

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':1200,'height':800})
        await pg.goto(URL)
        await pg.wait_for_function("window.__dzw && window.__dzw._torchMesh", timeout=15000)
        res=await pg.evaluate("""()=>{
          const d=window.__dzw, T=d._T; const me=d._torchMesh;
          const g=me.geometry; const pos=g.attributes.position; const N=pos.count;
          g.computeBoundingBox(); const bb=g.boundingBox;
          const size={x:bb.max.x-bb.min.x,y:bb.max.y-bb.min.y,z:bb.max.z-bb.min.z};
          // 가장 긴 축 = 토치 장축
          let axis='z'; if(size.x>=size.y&&size.x>=size.z)axis='x'; else if(size.y>=size.x&&size.y>=size.z)axis='y';
          const amin=bb.min[axis], amax=bb.max[axis], L=amax-amin;
          // 축을 40구간으로 나눠 각 구간의 최대반경(축과 수직 평면상) 계산
          const NB=40; const maxR=new Array(NB).fill(0); const cnt=new Array(NB).fill(0);
          const other=(axis==='x')?['y','z']:(axis==='y')?['x','z']:['x','y'];
          for(let i=0;i<N;i++){
            const v={x:pos.getX(i),y:pos.getY(i),z:pos.getZ(i)};
            const t=(v[axis]-amin)/L; let b=Math.floor(t*NB); if(b<0)b=0; if(b>=NB)b=NB-1;
            const r=Math.hypot(v[other[0]],v[other[1]]);
            if(r>maxR[b])maxR[b]=r; cnt[b]++;
          }
          return {axis, amin:+amin.toFixed(1), amax:+amax.toFixed(1), L:+L.toFixed(1),
            size:{x:+size.x.toFixed(1),y:+size.y.toFixed(1),z:+size.z.toFixed(1)},
            maxR:maxR.map(r=>+r.toFixed(1)), verts:N,
            note:'t=0 은 축 최소단(amin), t=1 은 축 최대단(amax). 반경 큰 쪽이 플랜지 원판.'};
        }""")
        print(json.dumps(res,ensure_ascii=False,indent=1))
        # 프로파일 시각 요약
        mr=res['maxR']; mx=max(mr) or 1
        print("\n축 %s, 길이 %.1fmm, %d버텍스" % (res['axis'],res['L'],res['verts']))
        print("t   반경(mm)  bar")
        for i,r in enumerate(mr):
            t=i/ (len(mr)-1)
            print("%.2f  %6.1f  %s" % (t, r, '#'*int(40*r/mx)))
        await br.close()

asyncio.run(main())
