# DXF 배치 서버 영구화 게이트 (2026-07-12)
# 1) 테스트 배치를 /save-dxf-layout POST → 2) 완전 새 브라우저(빈 localStorage)에서 자동 복원 확인
# 3) 새 업로드 기본위치가 서버 기준(_dxfServerTf) 반영되는지 확인
from playwright.sync_api import sync_playwright
import json, urllib.request, sys

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

# 1) 테스트 배치 저장 (실사용 파일이 이미 있으면 건드리지 않고 종료 — 데이터 보호)
import os
D = r"E:\도진팩토리\3D스캔및티칭시스템"
existed = os.path.exists(os.path.join(D, "dxf_saved_layout.json"))
if existed:
    print("SKIP_WRITE: 실사용 dxf_saved_layout.json 존재 — 덮어쓰지 않고 복원만 검사")
else:
    layout = [{"name": "_test.dxf", "tf": {"s": 1, "rot": 0, "tx": 123, "ty": -45},
               "locked": True, "content": json.dumps({"segs": [[0, 0, 100, 0], [100, 0, 100, 100]]})}]
    req = urllib.request.Request(BASE + "/save-dxf-layout", data=json.dumps(layout).encode(), method="POST")
    print("POST layout:", urllib.request.urlopen(req).status)
    req = urllib.request.Request(BASE + "/save-dxf-default", data=json.dumps({"s": 1, "rot": 0, "tx": 123, "ty": -45}).encode(), method="POST")
    print("POST default:", urllib.request.urlopen(req).status)

with sync_playwright() as p:
    b = p.chromium.launch()
    pg = b.new_page()  # 새 컨텍스트 = localStorage 완전 빈 상태
    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(4000)
    r = pg.evaluate("""() => { const a = window.__dzw;
      return {docs: (a._dxfDocs||[]).map(d=>({name:d.name, tx:d.tf&&d.tf.tx, locked:!!d.locked})),
              serverTf: a._dxfServerTf||null,
              ls: localStorage.getItem('dzw_dxf_saved_layout')===null}; }""")
    print("RESTORE(빈 브라우저):", json.dumps(r, ensure_ascii=False))
    ok = len(r["docs"]) > 0 and r["serverTf"] is not None
    print("RESULT:", "PASS" if ok else "FAIL", "| CONSOLE_ERRORS:", len(errs), errs[:3])
    b.close()
    # 테스트 데이터였다면 정리 (CEO 실저장이 깨끗하게 기록되도록)
    if not existed:
        for f in ("dxf_saved_layout.json", "dxf_default_tf.json"):
            try: os.remove(os.path.join(D, f))
            except OSError: pass
        print("CLEANUP: 테스트 파일 제거 완료")
    sys.exit(0 if ok else 1)
