"""
weld_path 오버레이 vs buildWeldFromJbi 경로 화면 포개짐 검증 (274mm 결함 해소 증명)
- 두 경로의 '실제 렌더된 월드 좌표'를 읽어 최근접 거리 비교
- 캡처
"""
import asyncio, sys, math
from playwright.async_api import async_playwright
TAG = sys.argv[1] if len(sys.argv) > 1 else 'BD'
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':1536,'height':864})
        errs=[]; pg.on('console', lambda m: errs.append(m.text) if m.type=='error' else None)
        await pg.goto(URL); await pg.wait_for_timeout(32000)
        # 오버레이 로드 + 용접경로 점 표시
        info = await pg.evaluate("""async ()=>{
          const a=window.__dzw;
          a.loadWeldPath();
          await new Promise(r=>setTimeout(r,2500));
          // buildWeldFromJbi 점들(weldDots) 월드좌표
          const T=a._T; const v=new T.Vector3();
          const jbiPts=[];
          (a.weldDots||[]).forEach(d=>{ if(d.geometry && d.geometry.type==='SphereGeometry'){ d.getWorldPosition(v); jbiPts.push([v.x,v.y,v.z]); }});
          // 오버레이 원천 truth점(_icpPathPts, _grp 로컬 mm) → 월드
          const grp=a._grp; const ov=[];
          (a._icpPathPts||[]).forEach(pt=>{ const w=grp.localToWorld(new T.Vector3(pt.x,pt.y,pt.z)); ov.push([w.x,w.y,w.z]); });
          return {jbi:jbiPts, ov:ov};
        }""")
        jbi=info['jbi']; ov=info['ov']
        print(f"buildWeldFromJbi 점 {len(jbi)}개, 오버레이 점 {len(ov)}개")
        # 각 jbi 점에 대해 최근접 오버레이 점 거리 (월드=m 단위 → mm 환산 ×1000)
        maxd=0; sm=0; cnt=0
        for pj in jbi:
            best=min(math.sqrt(sum((a-b)**2 for a,b in zip(pj,po))) for po in ov) if ov else 0
            maxd=max(maxd,best); sm+=best; cnt+=1
        if cnt:
            print(f"두 경로 최근접거리(월드 m): 최대 {maxd:.6f}  평균 {sm/cnt:.6f}")
            print(f"  → mm 환산: 최대 {maxd*1000:.3f}mm  평균 {sm/cnt*1000:.3f}mm")
            print("  판정:", "포개짐 ✅ (274mm 결함 해소)" if maxd*1000<1.0 else f"어긋남 ❌ {maxd*1000:.1f}mm")
        # 카메라: 용접부 위에서
        await pg.evaluate("(()=>{ const a=window.__dzw; if(a.orbit){a.orbit.phi=0.6;a.orbit.theta=0.9;a.orbit.r=4.2; a.updateCam();}})()")
        await pg.wait_for_timeout(1200)
        await pg.screenshot(path=f'shots/verify_{TAG}_path.png')
        print(f"캡처: shots/verify_{TAG}_path.png  콘솔에러 {len(errs)}")
        await br.close()
asyncio.run(main())
