# -*- coding: utf-8 -*-
# [2026-07-22] 진단(읽기전용): raycast faceIndex vs _origFaceIndex 중 어느 쪽이
#   _selectAutoRegion 의 올바른 씨앗인지 — "선택영역이 클릭점을 포함하는가"로 판정
import sys, io, json
from playwright.sync_api import sync_playwright

URL = "http://localhost:8091/DOZIKWORKS_OS_v5_locked.dc.html"

JS = r"""() => {
  const a=window.__dzw, E=window.DZW5_EDGEPATH;
  const cam=a.three.cam||a.three.camera, dom=a.three.rnd.domElement;
  const rect=dom.getBoundingClientRect();
  const RC=(window.THREE&&THREE.Raycaster)?THREE.Raycaster:a._ray.constructor;
  const ray=new RC(); const pos=a._knuckleMesh.geometry.attributes.position;
  const inv=a._knuckleMesh.matrixWorld.clone().invert();
  function stat(region,C){
    let best=1e9,x0=1e9,y0=1e9,z0=1e9,x1=-1e9,y1=-1e9,z1=-1e9;
    for(const t of region){ for(let k=0;k<3;k++){ const i=t*3+k;
      const vx=pos.getX(i),vy=pos.getY(i),vz=pos.getZ(i);
      if(vx<x0)x0=vx; if(vy<y0)y0=vy; if(vz<z0)z0=vz;
      if(vx>x1)x1=vx; if(vy>y1)y1=vy; if(vz>z1)z1=vz;
      const d=Math.hypot(vx-C.x,vy-C.y,vz-C.z); if(d<best)best=d; }}
    return {n:region.size, mm:+Math.max(x1-x0,y1-y0,z1-z0).toFixed(0), dist:+best.toFixed(1)};
  }
  const out=[];
  const grid=[];for(let y=0.2;y<0.85;y+=0.08)for(let x=0.2;x<0.85;x+=0.08)grid.push([x,y]);
  for(const [gx,gy] of grid){
    const mx=gx*2-1, my=-(gy*2-1);
    ray.setFromCamera({x:mx,y:my},cam);
    const h=ray.intersectObjects([a._knuckleMesh],true);
    if(!h.length){ continue; }
    const hit=h[0], C=hit.point.clone().applyMatrix4(inv);
    const of=E._origFaceIndex(a._knuckleMesh,hit.faceIndex);
    function triDist(t){ let best=1e9; for(let k=0;k<3;k++){ const i=t*3+k;
      const d=Math.hypot(pos.getX(i)-C.x,pos.getY(i)-C.y,pos.getZ(i)-C.z); if(d<best)best=d;} return +best.toFixed(1); }
    out.push({gx,gy,raycastFace:hit.faceIndex,origFace:of,
      seedTriDist_orig:triDist(of), seedTriDist_raw:triDist(hit.faceIndex),
      byOrig:stat(E._selectAutoRegion(a._knuckleMesh,of),C),
      byRaw: stat(E._selectAutoRegion(a._knuckleMesh,hit.faceIndex),C)});
  }
  return out;
}"""

with sync_playwright() as p:
    b=p.chromium.launch(); pg=b.new_page(viewport={"width":1600,"height":900})
    pg.goto(URL)
    pg.wait_for_function("window.__dzw && window.__dzw._knuckleMesh && window.DZW5_EDGEPATH && window.__dzw.three", timeout=60000)
    pg.wait_for_timeout(4000)
    res=pg.evaluate(JS); b.close()
sys.stdout=io.TextIOWrapper(sys.stdout.buffer,encoding="utf-8")
for r in res: print(json.dumps(r,ensure_ascii=False))
