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;
            if (!app) return {error: '__dzw 없음'};
            const T = app._T;
            const grp = app._grp;
            const ang = app.gj;
            if (!ang) return {error: 'gj 없음'};

            // 각 관절 그룹의 world position 확인
            const worldPos = {};
            for (const a of ['S','L','U','R','B','T']) {
                if (ang[a]) {
                    const v = new T.Vector3();
                    ang[a].getWorldPosition(v);
                    worldPos[a] = {x: +v.x.toFixed(4), y: +v.y.toFixed(4), z: +v.z.toFixed(4)};
                }
            }

            // _grp 내 전체 mesh 목록 (position, parent chain)
            const meshes = [];
            grp.traverse(o => {
                if (o.isMesh) {
                    const v = new T.Vector3();
                    o.getWorldPosition(v);
                    // parent 체인 이름
                    let chain = [];
                    let cur = o;
                    while (cur && cur !== grp) {
                        chain.unshift(cur.name || cur.type || 'Group');
                        cur = cur.parent;
                    }
                    meshes.push({
                        uuid: o.uuid.slice(0,8),
                        chain: chain.join(' > '),
                        wx: +v.x.toFixed(3),
                        wy: +v.y.toFixed(3),
                        wz: +v.z.toFixed(3),
                        geomCount: o.geometry ? o.geometry.attributes.position.count : 0
                    });
                }
            });

            // robotGrp world position
            const rgPos = new T.Vector3();
            if (app._robotGrp) app._robotGrp.getWorldPosition(rgPos);

            return {
                grpScale: grp.scale.x,
                grpPosZ: grp.position.z,
                rgWorld: {x: +rgPos.x.toFixed(4), y: +rgPos.y.toFixed(4), z: +rgPos.z.toFixed(4)},
                jointWorldPos: worldPos,
                meshCount: meshes.length,
                meshes: meshes.slice(0, 30)
            };
        }""")

        print("=== _grp 스케일:", r.get('grpScale'), "| _grp.z:", r.get('grpPosZ'))
        print("=== robotGrp world:", r.get('rgWorld'))
        print("\n=== 관절 world 위치 ===")
        for a, v in (r.get('jointWorldPos') or {}).items():
            print(f"  {a}: {v}")
        print(f"\n=== 전체 메시 {r.get('meshCount')}개 (처음 30개) ===")
        for m in (r.get('meshes') or []):
            print(f"  [{m['uuid']}] {m['chain']} | world({m['wx']},{m['wy']},{m['wz']}) | verts:{m['geomCount']}")

        # 스크린샷 (3D만 크롭)
        await pg.screenshot(path='bt_diagnose.png', clip={'x':220,'y':40,'width':900,'height':700})
        print('\n스크린샷 → bt_diagnose.png')
        await br.close()

asyncio.run(main())
