# 경로생성 노란 TCP 점 세션저장·복원 게이트 (2026-07-12)
# GEN: opts로 경로 생성 → COLLECT: pathGen 포함 → RELOAD 후 RESTORE: 점 재생성 확인
from playwright.sync_api import sync_playwright
import json, sys

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

with sync_playwright() as p:
    b = p.chromium.launch()
    pg = b.new_page()
    errs = []
    pg.on("pageerror", lambda e: errs.append(str(e)))
    pg.goto(URL)
    pg.wait_for_function("window.__dzw && window.__dzw._knuckleMesh", timeout=60000)
    pg.wait_for_timeout(2000)

    # 1) 제품 로컬좌표 기준 opts로 경로 생성 (판 위 임의 100mm 엣지)
    r = pg.evaluate("""() => {
      const a = window.__dzw;
      const opts = {p1L:[0.1,0.1,0.05], p2L:[0.2,0.1,0.05], interval_mm:50, wa:53.6, ta:54.1, offset_mm:1, side:1};
      DZW5_APP_MEASURE._pathGenerate(a, opts);
      return {n:(a._pathResultMeshes||[]).length, st:!!a._pathGenState};
    }""")
    print("GEN:", "PASS" if r["n"] > 0 and r["st"] else "FAIL", r)

    # 2) collect()에 pathGen 포함 + 수동저장
    c = pg.evaluate("""() => {
      const d = DZW5_PROJECT.collect();
      localStorage.setItem('dzw_project_autosave', JSON.stringify(d));
      return !!d.pathGen;
    }""")
    print("COLLECT:", "PASS" if c else "FAIL")

    # 3) 새로고침 → 자동복원으로 점 재생성 확인
    pg.reload()
    pg.wait_for_function("window.__dzw && window.__dzw._knuckleMesh", timeout=60000)
    try:
        pg.wait_for_function("window.__dzw._pathResultMeshes && window.__dzw._pathResultMeshes.length>0", timeout=20000)
        r2 = pg.evaluate("() => ({n:window.__dzw._pathResultMeshes.length, st:!!window.__dzw._pathGenState})")
        print("RESTORE:", "PASS", r2)
    except Exception:
        print("RESTORE: FAIL (20초 내 점 미복원)")
        sys.exit(1)
    finally:
        # 테스트 잔여물 정리 (실사용 자동저장 오염 방지)
        pg.evaluate("""() => { const d=JSON.parse(localStorage.getItem('dzw_project_autosave')||'{}');
          delete d.pathGen; localStorage.setItem('dzw_project_autosave', JSON.stringify(d)); }""")
    print("CONSOLE_ERRORS:", len(errs), errs[:3])
    b.close()
