import asyncio
from playwright.async_api import async_playwright

async def main():
    async with async_playwright() as p:
        br = await p.chromium.launch(headless=True)
        pg = await br.new_page()
        await pg.set_viewport_size({'width':1536,'height':1024})
        await pg.goto('http://localhost:8090/DOZIKWORKS_OS_v4_pathcreate.dc.html')
        await pg.wait_for_timeout(18000)

        r = await pg.evaluate("""() => {
            const app = window.__dzw;
            const T = app._T;
            const ang = app.gj;
            if (!ang) return {error: 'gj 없음'};

            function wPos(obj) {
                app._grp.updateMatrixWorld(true);
                const v = new T.Vector3();
                obj.getWorldPosition(v);
                return [+(v.x*1000).toFixed(1), +(v.y*1000).toFixed(1), +(v.z*1000).toFixed(1)];
            }

            // 현재 ang rotation.z 값 직접 읽기
            const currentRot = {};
            for (const a of ['S','L','U','R','B','T']) {
                if (ang[a]) currentRot[a] = +(ang[a].rotation.z * 180/Math.PI).toFixed(3);
            }

            // 현재 상태 U 위치
            app._grp.updateMatrixWorld(true);
            const uPosLive = wPos(ang.U);

            // 테스트1: L=-24.148 U=0
            app.poseRobot({S:0, L:-24.148, U:0, R:0, B:0, T:0});
            app._grp.updateMatrixWorld(true);
            const uPos_L_U0 = wPos(ang.U);

            // 테스트2: L=-24.148 U=-49.205 (sign fix에서 ang.U.rotation.z = +49.205)
            app.poseRobot({S:0, L:-24.148, U:-49.205, R:0, B:0, T:0});
            app._grp.updateMatrixWorld(true);
            const uPos_L_U49 = wPos(ang.U);
            const angURotAfter = +(ang.U.rotation.z * 180/Math.PI).toFixed(3);

            // 테스트3: 현재 관절각 그대로 (sign fix 적용된 상태)
            app.poseRobot(app.state.joints);
            app._grp.updateMatrixWorld(true);
            const uPos_current = wPos(ang.U);

            return {
                currentRot,
                uPosLive,
                uPos_L_U0,
                uPos_L_U49,
                angURotAfterTest2: angURotAfter,
                uPos_current,
                stateJoints: app.state.joints,
            };
        }""")

        print("=== 현재 ang.rotation.z (라이브 페이지) ===")
        for a, v in (r.get('currentRot') or {}).items():
            print(f"  ang.{a}.rotation.z = {v}°")

        print(f"\n라이브 U 위치: {r.get('uPosLive')}")
        print(f"테스트1 (L=-24.148°, U=0°): {r.get('uPos_L_U0')}")
        print(f"테스트2 (L=-24.148°, U=-49.205°): {r.get('uPos_L_U49')}  (ang.U.rz = {r.get('angURotAfterTest2')}°)")
        print(f"테스트3 (state.joints 그대로): {r.get('uPos_current')}")
        print(f"\nstate.joints: {r.get('stateJoints')}")

        await br.close()

asyncio.run(main())
