import asyncio
from playwright.async_api import async_playwright
import math

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

            // weld_path.json에서 poses[0] 가져오기
            const posesArr = app._csvPoses;
            const pose0 = posesArr && posesArr.length > 0 ? posesArr[0] : null;
            const pose50 = posesArr && posesArr.length > 50 ? posesArr[50] : null;

            const results = [];

            for (const [label, pose] of [['pose0', pose0], ['pose50', pose50]]) {
                if (!pose) continue;
                // 포즈 적용
                app.poseRobot(pose);
                app._grp.updateMatrixWorld(true);

                // TCP sphere 위치
                let tcpPos = null;
                app._grp.traverse(o => {
                    if (o.isMesh && o.geometry && o.geometry.attributes.position && o.geometry.attributes.position.count === 357) {
                        tcpPos = wPosMM(o);
                    }
                });

                // FK TCP
                const fk = app.fk(pose);
                const fkMM = [+fk.x.toFixed(1), +fk.y.toFixed(1), +fk.z.toFixed(1)];

                // T joint 위치
                const tPos = wPosMM(ang.T);

                results.push({label, pose, fkMM, tcpPos, tPos});
            }

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

            return {results};
        }""")

        print("=== 동일 포즈에서 FK vs TCP sphere 비교 (sign fix 적용) ===\n")
        for row in r.get('results', []):
            label = row['label']
            pose = row['pose']
            fk = row['fkMM']
            tcp = row['tcpPos']
            t = row['tPos']

            print(f"[{label}]")
            print(f"  포즈: S={pose.get('S',0):.2f}° L={pose.get('L',0):.2f}° U={pose.get('U',0):.2f}° R={pose.get('R',0):.2f}° B={pose.get('B',0):.2f}° T={pose.get('T',0):.2f}°")
            print(f"  FK TCP:      {fk} mm")
            print(f"  TCP sphere:  {tcp} mm")

            if fk and tcp:
                diff = [fk[0]-tcp[0], fk[1]-tcp[1], fk[2]-tcp[2]]
                dist = math.sqrt(sum(d**2 for d in diff))
                print(f"  오차:        {[f'{d:.1f}' for d in diff]} mm → 거리={dist:.1f}mm")
                ok = dist < 100
                print(f"  판정: {'✅ 일치 (100mm 이내)' if ok else '❌ 불일치'}")
            print()

        await br.close()

asyncio.run(main())
