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 없음'};

            // 행렬 업데이트 강제
            app._grp.updateMatrixWorld(true);

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

            function getWorldRotMatrix(obj) {
                const m = new T.Matrix4();
                obj.updateWorldMatrix(true, false);
                m.copy(obj.matrixWorld);
                // scale 제거 (0.001)
                const e = m.elements; // column-major
                // 칼럼 0 (local X 방향)
                const scale = Math.sqrt(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]);
                return {
                    localX: [+(e[0]/scale).toFixed(3), +(e[1]/scale).toFixed(3), +(e[2]/scale).toFixed(3)],
                    localY: [+(e[4]/scale).toFixed(3), +(e[5]/scale).toFixed(3), +(e[6]/scale).toFixed(3)],
                    localZ: [+(e[8]/scale).toFixed(3), +(e[9]/scale).toFixed(3), +(e[10]/scale).toFixed(3)],
                };
            }

            // HOME 포즈에서 확인
            const home = {S:0, L:0, U:0, R:0, B:0, T:0};
            app.poseRobot(home);
            app._grp.updateMatrixWorld(true);

            const homeResult = {};
            for (const a of ['S','L','U','R','B','T']) {
                if (ang[a]) {
                    homeResult[a] = {
                        pos: getWorldPosMM(ang[a]),
                        rot: getWorldRotMatrix(ang[a])
                    };
                }
            }
            // TCP sphere at home
            let tcpHomeMM = null;
            app._grp.traverse(o => {
                if (o.isMesh && o.geometry && o.geometry.attributes.position && o.geometry.attributes.position.count === 357) {
                    tcpHomeMM = getWorldPosMM(o);
                }
            });
            const fkHome = app.fk(home);

            // 원래 포즈 복원
            app.poseRobot(app.state.joints);
            app._grp.updateMatrixWorld(true);

            return {
                home: {
                    joints: homeResult,
                    tcpMesh: tcpHomeMM,
                    fk: {x: +fkHome.x.toFixed(1), y: +fkHome.y.toFixed(1), z: +fkHome.z.toFixed(1)}
                },
                urdf: window.DZW_DATA.urdf.map(j => ({a:j.a, xyz:j.xyz, rpy:j.rpy.map(v=>+(v*180/Math.PI).toFixed(1)), sign:j.sign}))
            };
        }""")

        print("=== HOME 포즈 (0°) 관절 월드 위치/방향 ===")
        home = r.get('home', {})
        for a, v in (home.get('joints') or {}).items():
            pos = v['pos']
            rot = v['rot']
            print(f"  {a}: pos={pos}")
            print(f"     localX→world={rot['localX']}, localZ→world={rot['localZ']}")

        print(f"\nFK HOME TCP: {home.get('fk')}")
        print(f"TCP mesh HOME: {home.get('tcpMesh')}")

        print("\n=== URDF ===")
        for j in (r.get('urdf') or []):
            print(f"  {j['a']}: xyz={j['xyz']}, rpy(deg)={j['rpy']}, sign={j['sign']}")

        await br.close()

asyncio.run(main())
