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)];
            }

            function wDir(obj) {
                const m = new T.Matrix4();
                obj.updateWorldMatrix(true, false);
                m.extractRotation(obj.matrixWorld);
                const scale = Math.sqrt(m.elements[0]**2 + m.elements[1]**2 + m.elements[2]**2) * 0.001;
                return {
                    X: [+(m.elements[0]/scale/1000).toFixed(3), +(m.elements[1]/scale/1000).toFixed(3), +(m.elements[2]/scale/1000).toFixed(3)],
                    Z: [+(m.elements[8]/scale/1000).toFixed(3), +(m.elements[9]/scale/1000).toFixed(3), +(m.elements[10]/scale/1000).toFixed(3)],
                };
            }

            const results = [];

            // L만 여러 각도로 테스트
            for (const L_angle of [0, -24.148, -45, -90]) {
                const j = {S:0, L:L_angle, U:0, R:0, B:0, T:0};
                app.poseRobot(j);
                app._grp.updateMatrixWorld(true);
                const u = wPos(ang.U);
                const l = wPos(ang.L);
                const fk = app.fk(j);
                results.push({
                    L_angle,
                    L_world: l,
                    U_world: u,
                    fk_tcp: [+fk.x.toFixed(1), +fk.y.toFixed(1), +fk.z.toFixed(1)],
                    ang_L_rz: +(ang.L.rotation.z * 180/Math.PI).toFixed(3)
                });
            }

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

            return {results};
        }""")

        print("=== L 각도별 U joint 위치 ===")
        for row in r.get('results', []):
            L = row['L_angle']
            Lw = row['L_world']
            Uw = row['U_world']
            fk = row['fk_tcp']
            arZ = row['ang_L_rz']
            print(f"\nL={L}° (ang.L.rotation.z={arZ}°)")
            print(f"  L world: {Lw}")
            print(f"  U world: {Uw}")
            print(f"  U-L diff: [{Uw[0]-Lw[0]:.1f}, {Uw[1]-Lw[1]:.1f}, {Uw[2]-Lw[2]:.1f}]")
            print(f"  FK TCP: {fk}")

        await br.close()

asyncio.run(main())
