import asyncio
from playwright.async_api import async_playwright

JS_OVERLAY = (
    "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(' ');"
    "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:0xff0000,transparent:true,opacity:0.6,wireframe:true}));"
    "m.raycast=()=>{};"
    "grp.add(m);"
    "return 'done';"
    "}"
)

async def shot():
    async with async_playwright() as p:
        br = await p.chromium.launch(channel='msedge', headless=True)
        pg = await br.new_page(viewport={'width':1536,'height':864})
        await pg.goto('http://localhost:8090/DOZIKWORKS_OS_v5_locked.dc.html')
        print('로딩 45초...')
        await pg.wait_for_timeout(45000)
        r = await pg.evaluate(JS_OVERLAY)
        print('오버레이:', r)
        await pg.wait_for_timeout(2000)
        await pg.evaluate("(()=>{ const a=window.__dzw; a.orbit.phi=0.05; a.orbit.r=9; a.updateCam(); })()")
        await pg.wait_for_timeout(800)
        await pg.screenshot(path='ov_top.png')
        print('top 저장')
        await pg.evaluate("(()=>{ const a=window.__dzw; a.orbit.phi=1.2; a.orbit.theta=-1.57; a.orbit.r=7; a.updateCam(); })()")
        await pg.wait_for_timeout(800)
        await pg.screenshot(path='ov_front.png')
        print('front 저장')
        await br.close()

asyncio.run(shot())
