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)

        # FRONT 뷰 + zoom out으로 전체 로봇 보기
        await pg.evaluate("""() => {
            const app = window.__dzw;
            // FRONT 뷰 설정
            app.setView('FRONT');
            // zoom out해서 전체 씬 보이게
            if (app.orbit) {
                app.orbit.r = 8.0;
                app.orbit.tgt.set(0.1, 0, 0.2);
            }
            app.updateCam();
        }""")
        await pg.wait_for_timeout(500)

        # TCP 위치와 관절 월드 위치 확인
        info = await pg.evaluate("""() => {
            const app = window.__dzw;
            const T = app._T;
            const ang = app.gj;
            const joints = {};
            for (const a of ['S','L','U','R','B','T']) {
                if (ang && ang[a]) {
                    const v = new T.Vector3();
                    ang[a].getWorldPosition(v);
                    joints[a] = {x:+v.x.toFixed(3), y:+v.y.toFixed(3), z:+v.z.toFixed(3)};
                }
            }
            // TCP sphere 월드 위치
            const tcpSphere = app._tcpSphere;
            let tcpSphereWorld = null;
            if (tcpSphere) {
                const v = new T.Vector3();
                tcpSphere.getWorldPosition(v);
                tcpSphereWorld = {x:+v.x.toFixed(3), y:+v.y.toFixed(3), z:+v.z.toFixed(3)};
            }
            return {
                currentState: {
                    S: app.state.joints.S,
                    L: app.state.joints.L,
                    U: app.state.joints.U,
                    R: app.state.joints.R,
                    B: app.state.joints.B,
                    T: app.state.joints.T,
                },
                tcp: app.state.tcp,
                joints,
                tcpSphereWorld
            };
        }""")
        print("현재 관절 각도:", info.get('currentState'))
        print("FK TCP:", info.get('tcp'))
        print("관절 월드 위치:")
        for a, v in (info.get('joints') or {}).items():
            print(f"  {a}: {v}")
        print("TCP sphere 월드:", info.get('tcpSphereWorld'))

        await pg.screenshot(path='front_full.png', clip={'x':0,'y':0,'width':1536,'height':1024})
        print('스크린샷 → front_full.png')
        await br.close()

asyncio.run(main())
