"""Offline preview: run the Lua renderer against a fake Gui and rasterise the calls."""
import sys
from pathlib import Path
from lupa.luajit21 import LuaRuntime
from PIL import Image,ImageDraw,ImageFont
R=Path(__file__).resolve().parents[1]
def render(values,out,W=1920,H=1080,clock=0.0,crop=None,bg=None,scale=1):
 L=LuaRuntime(unpack_returned_tuples=True)
 L.execute('''ops={}
 sr={World={},Gui={rect=function(g,p,s,c) ops[#ops+1]={'r',p[1],p[2],p[3],s[1],s[2],c[1],c[2],c[3],c[4]} return #ops end,
  text=function(g,s,f,size,f2,p,c) ops[#ops+1]={'t',p[1],p[2],p[3] or 0,size,s,c[1],c[2],c[3],c[4]} return #ops end,
  destroy_rect=function() end,destroy_text=function() end},
  Vector2=function(x,y) return {x,y} end,Vector3=function(x,y,z) return {x,y,z} end,Color=function(a,r,g,b) return {a,r,g,b} end}''')
 C=L.execute((R/'src/config.lua').read_text())(None);C.scale=scale
 ART=L.execute((R/'src/art.lua').read_text())
 FB=L.execute((R/'src/render.lua').read_text())(L.globals().sr,C)
 D=L.execute((R/'src/render_mech.lua').read_text())(L.globals().sr,C,ART,FB)
 D.gui='G'
 v=L.execute('return function(t) return t end')(L.eval(values))
 v.clock=clock
 D.draw(W,H,v)
 ops=L.globals().ops;items=[]
 for i in range(1,len(ops)+1):
  o=ops[i];items.append([o[j] for j in range(1,len(o)+1)])
 items.sort(key=lambda o:o[3])
 img=(Image.open(bg).convert('RGB').resize((W,H)) if bg else Image.new('RGB',(W,H),(64,72,60)))
 d=ImageDraw.Draw(img,'RGBA')
 font=lambda s:ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSansMono-Bold.ttf',max(6,int(s*0.95)))
 nr=0
 for o in items:
  if o[0]=='r':
   _,x,y,z,w,h,a,r,g,b=o;nr+=1
   d.rectangle([x,H-y-h,x+w-1,H-y-1],fill=(r,g,b,a))
  else:
   _,x,y,z,size,s,a,r,g,b=o
   d.text((x,H-y),s,font=font(size),fill=(r,g,b,a),anchor='ls')
 if crop:img=img.crop(crop)
 img.save(out);return nr,len(items)
if __name__=='__main__':
 pass
