import asyncio
from playwright.async_api import async_playwright

JS_ADD = r"""
async () => {
    const T=window.THREE, grp=window.__dzw._grp;
    const r=await fetch('jeonban.obj'); const txt=await r.text();
    const lines=txt.split('\n'), vBuf=[], posArr=[];
    for(const line of lines){
        const p=line.trim().split(/\s+/);
        if(p[0]==='v'){ vBuf.push(parseFloat(p[1]),parseFloat(p[2]),parseFloat(p[3])); }
        else if(p[0]==='f'){
            const verts=[];
            for(let i=1;i<p.length;i++){ const sp=p[i].split('/'); verts.push((parseInt(sp[0])-1)*3); }
            for(let i=1;i<verts.length-1;i++)
                for(const vi of [verts[0],verts[i],verts[i+1]])
                    posArr.push(vBuf[vi],vBuf[vi+1],vBuf[vi+2]);
        }
    }
    const g=new T.BufferGeometry();
    g.setAttribute('position',new T.BufferAttribute(new Float32Array(posArr),3));
    g.computeVertexNormals();
    const m=new T.Mesh(g,new T.MeshPhongMaterial({color:0xff2200,transparent:true,opacity:0.6,wireframe:true}));
    grp.add(m);
    return 'done';
}
"""

JS_CAM = "(a)=>{ const app=window.__dzw; app.orbit.theta=a.theta; app.orbit.phi=a.phi; app.orbit.r=a.r; app.updateCam(); }"

VIEWS = [
    ('top',    -1.57, 0.05, 6.0),
    ('front',  -1.57, 1.2,  5.0),
    ('side',    0.0,  1.2,  5.0),
]

async def check():
    async with async_playwright() as p:
        br = await p.chromium.launch(channel='msedge', headless=False, args=['--start-maximized'])
        ctx = await br.new_context(no_viewport=True)
        pg = await ctx.new_page()
        await pg.goto('http://localhost:8090/DOZIKWORKS_OS_v5_cleanpath.dc.html')
        print('로딩 중...')
        await pg.wait_for_timeout(30000)
        await pg.evaluate(JS_ADD)
        await pg.wait_for_timeout(2000)
        for name, theta, phi, r in VIEWS:
            await pg.evaluate(JS_CAM, {'theta': theta, 'phi': phi, 'r': r})
            await pg.wait_for_timeout(600)
            await pg.screenshot(path=f'cmp_{name}.png')
            print(f'{name} 저장')
        await br.close()

asyncio.run(check())
