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)

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

            function getWorldPos(obj) {
                const v = new T.Vector3();
                obj.getWorldPosition(v);
                // _grp local (mm) = world / 0.001
                return {x: +(v.x/0.001).toFixed(1), y: +(v.y/0.001).toFixed(1), z: +(v.z/0.001).toFixed(1)};
            }

            // 각 관절 world position (mm)
            const jMM = {};
            for (const a of ['S','L','U','R','B','T']) {
                if (ang[a]) jMM[a] = getWorldPos(ang[a]);
            }

            // TCP sphere (357 verts) 찾기
            let tcpMeshPos = null;
            app._grp.traverse(o => {
                if (o.isMesh && o.geometry && o.geometry.attributes.position && o.geometry.attributes.position.count === 357) {
                    tcpMeshPos = getWorldPos(o);
                }
            });

            // 현재 FK TCP
            const fk = app.fk(app.state.joints);

            // HOME 포즈 적용
            const home = {S:0, L:0, U:0, R:0, B:0, T:0};
            app.poseRobot(home);
            const fkHome = app.fk(home);

            // HOME에서 TCP mesh world pos
            let tcpHomePos = null;
            app._grp.traverse(o => {
                if (o.isMesh && o.geometry && o.geometry.attributes.position && o.geometry.attributes.position.count === 357) {
                    tcpHomePos = getWorldPos(o);
                }
            });

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

            return {
                currentJoints: app.state.joints,
                fkCurrent: {x: +fk.x.toFixed(1), y: +fk.y.toFixed(1), z: +fk.z.toFixed(1)},
                tcpMeshMM: tcpMeshPos,
                fkHome: {x: +fkHome.x.toFixed(1), y: +fkHome.y.toFixed(1), z: +fkHome.z.toFixed(1)},
                tcpHomeMM: tcpHomePos,
                jointsMM: jMM,
                // T joint local z축 방향 (tcp offset이 이 방향으로 더해짐)
                tLocalZ: (() => {
                    const dir = new T.Vector3(0,0,1);
                    ang.T.localToWorld(dir);
                    const origin = new T.Vector3(0,0,0);
                    ang.T.localToWorld(origin);
                    const v = dir.sub(origin);
                    return {x: +v.x.toFixed(3), y: +v.y.toFixed(3), z: +v.z.toFixed(3)};
                })(),
            };
        }""")

        print("=== 현재 포즈 ===")
        print("관절각:", result.get('currentJoints'))
        print("FK TCP (mm):", result.get('fkCurrent'))
        print("TCP mesh 위치 (mm):", result.get('tcpMeshMM'))
        fk = result.get('fkCurrent') or {}
        tcp = result.get('tcpMeshMM') or {}
        if fk and tcp:
            dx = fk['x'] - tcp['x']
            dy = fk['y'] - tcp['y']
            dz = fk['z'] - tcp['z']
            import math
            dist = math.sqrt(dx**2+dy**2+dz**2)
            print(f"차이: dx={dx:.1f} dy={dy:.1f} dz={dz:.1f} → 거리={dist:.1f}mm")

        print("\n=== HOME 포즈 (0°) ===")
        print("FK TCP (mm):", result.get('fkHome'))
        print("TCP mesh 위치 (mm):", result.get('tcpHomeMM'))

        print("\n=== 관절 위치 (mm) ===")
        for a, v in (result.get('jointsMM') or {}).items():
            print(f"  {a}: ({v['x']}, {v['y']}, {v['z']})")

        print("\nT 관절 Local Z축 방향 (world):", result.get('tLocalZ'))

        await br.close()

asyncio.run(main())
