# -*- coding: utf-8 -*-
# [2026-07-22] 판선택 복원(0150d8b) 실측: 씨앗 7개에 대해 선택 삼각형수 + bbox 최대축(mm)
#   사용: python _plate_restore_measure.py <라벨>
import sys, io, json
from playwright.sync_api import sync_playwright

URL = "http://localhost:8091/DOZIKWORKS_OS_v5_locked.dc.html"
SEEDS = [130, 2830, 3572, 7513, 8424, 1816, 5000]

JS = r"""
(seeds) => {
  const app = window.__dzw;
  if(!app || !app._knuckleMesh) return {err:'mesh not loaded'};
  const E = window.DZW5_EDGEPATH;
  const geo = app._knuckleMesh.geometry, pos = geo.attributes.position;
  function bboxMax(region){
    let 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 x=pos.getX(i), y=pos.getY(i), z=pos.getZ(i);
      if(x<x0)x0=x; if(y<y0)y0=y; if(z<z0)z0=z;
      if(x>x1)x1=x; if(y>y1)y1=y; if(z>z1)z1=z; } }
    return Math.max(x1-x0, y1-y0, z1-z0);
  }
  const rows=[];
  for(const s of seeds){
    const r={seed:s};
    try{ const a=E._selectAutoRegion(app._knuckleMesh,s); r.autoN=a.size; r.autoMM=+bboxMax(a).toFixed(0); }
    catch(e){ r.autoErr=e.message; }
    try{ if(E._selectGroupRegion){ const g=E._selectGroupRegion(app,app._knuckleMesh,s); r.grpN=g.size; r.grpMM=+bboxMax(g).toFixed(0); } }
    catch(e){ r.grpErr=e.message; }
    rows.push(r);
  }
  return {rows, tris: pos.count/3};
}
"""

def main():
    label = sys.argv[1] if len(sys.argv) > 1 else "run"
    with sync_playwright() as p:
        b = p.chromium.launch()
        pg = b.new_page()
        errs = []
        pg.on("console", lambda m: errs.append(m.text) if m.type == "error" else None)
        pg.goto(URL, wait_until="networkidle", timeout=30000)
        pg.wait_for_function("() => window.__dzw && window.__dzw._knuckleMesh", timeout=20000)
        res = pg.evaluate(JS, SEEDS)
        b.close()
    print("[" + label + "] " + json.dumps(res, ensure_ascii=False))
    if errs:
        print("JS errors:", errs[:5])

if __name__ == "__main__":
    sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
    main()
