"""Render the existing procedural meshes as orthographic study plates. Run from any directory with Python, Pillow, Playwright and Chrome."""
from pathlib import Path
from base64 import b64decode
from io import BytesIO
from tempfile import TemporaryDirectory

from PIL import Image, ImageDraw, ImageFont
from playwright.sync_api import sync_playwright

OUT = Path(__file__).resolve().parent
PROTOTYPE = OUT.parents[2] / "prototype" / "academy"
PAPER = "#f4f2e9"
INK = "#263c37"
MUTED = "#54635b"
FONTS = Path("C:/Windows/Fonts")


def font(name, size):
    return ImageFont.truetype(str(FONTS / name), size)


def setup_source():
    js = (PROTOTYPE / "harbour.js").read_text("utf-8")
    # Keep group membership explicit across the author's draw-call baking step.
    start = js.index("  for(let i=-11;i<=11;i++) box(base")
    end = js.index("  // Open, tapered hull", start)
    js = js[:start] + "  const rails=group(scene);\n" + js[start:end].replace("box(base", "box(rails") + js[end:]
    start = js.index("  cylinder(quay,0,1.21")
    end = js.index("  cylinder(turret,0,1.54", start)
    js = js[:start] + "  const foundation=group(scene);\n" + js[start:end].replace("cylinder(quay", "cylinder(foundation") + js[end:]
    js = js.replace("[base,quay,barge,truck,turret,load,tub,drum,wheel,sheave]", "[rails,foundation,base,quay,barge,truck,turret,load,tub,drum,wheel,sheave]")
    return js[:js.index("  new ResizeObserver")] + RENDER_API + "\n})();"


RENDER_API = """
  window.sheetViews = key => {
    const all=[turret,truck,barge,base,quay,rails,foundation];
    all.forEach(o => o.visible=true);
    load.visible=true;
    value=27;show();
    if(key!=='scene') {
      const visible={crane:[turret,foundation],wagon:[truck],barge:[barge],quay:[quay,rails],tub:[turret]}[key];
      all.forEach(o => o.visible=visible.includes(o));
    }
    // A standalone tub stays in its rigid rig, and all its ore retains the current pose.
    const tubHidden=[];
    if(key==='tub') {
      turret.children.forEach(o=>{if(o!==load && o.visible){tubHidden.push(o);o.visible=false;}});
    } else if(key==='crane') {
      load.visible=false;
    }
    scene.updateMatrixWorld(true);
    const points=[];
    scene.traverseVisible(obj=>{
      if(!obj.isMesh)return;
      const pos=obj.geometry.attributes.position;
      for(let i=0;i<pos.count;i++) points.push(new THREE.Vector3().fromBufferAttribute(pos,i).applyMatrix4(obj.matrixWorld));
    });
    const center=new THREE.Box3().setFromPoints(points).getCenter(new THREE.Vector3());
    // End-on and broadside directions swap for the jib, whose working plane runs along Z.
    const dirs=key==='crane' ? [[1,0,0],[0,0,1],[0,1,0],[1,.62,1]] : [[0,0,1],[1,0,0],[0,1,0],[1,.62,1]];
    const W=key==='scene'?1500:700, H=key==='scene'?730:370;
    const specs=dirs.map(direction=>{
      camera.position.copy(center).addScaledVector(new THREE.Vector3(...direction).normalize(),45);
      camera.up.set(0,1,0);
      if(direction[1]===1) camera.up.set(0,0,-1);
      camera.lookAt(center);camera.updateMatrixWorld(true);
      const bounds=new THREE.Box3();
      const p=new THREE.Vector3();
      for(const point of points) bounds.expandByPoint(p.copy(point).applyMatrix4(camera.matrixWorldInverse));
      const size=bounds.getSize(p);
      const units=Math.max(size.x/W,size.y/H)*1.10;
      return {bounds,units,position:camera.position.clone(),up:camera.up.clone()};
    });
    const common=Math.max(...specs.slice(0,3).map(s=>s.units));
    renderer.setPixelRatio(1);
    renderer.setSize(W,H,false);
    scene.background.set(0xf4f2e9);
    const imgs=specs.map(({bounds,units,position,up},i)=>{
      const scale=i===3 ? units : common;
      const c=bounds.getCenter(new THREE.Vector3());
      camera.position.copy(position);camera.up.copy(up);camera.lookAt(center);
      Object.assign(camera,{left:c.x-scale*W/2,right:c.x+scale*W/2,bottom:c.y-scale*H/2,top:c.y+scale*H/2});
      camera.updateProjectionMatrix();
      renderer.render(scene,camera);
      return renderer.domElement.toDataURL('image/png').split(',')[1];
    });
    tubHidden.forEach(o=>o.visible=true);
    return imgs;
  };
"""

ASSETS = {
    "barge": ("Рудная баржа", "Сопоставить ватерлинию и шпангоуты с листом Сильяна 1837 года. Местный корпус требует обмеров."),
    "crane": ("Причальный кран", "Сверить опору и ось поворота. Литография Фэрберна 1852 года показывает другой тип стрелы."),
    "wagon": ("Рудный вагон", "По листу HJ 1876 года сверять устройство ходовой. Кузов и колея вагона Törefors остаются условными."),
    "quay": ("Причал и рельсовый путь", "Проверить свайное поле и отметку настила по съёмке. Снимок 1929 года фиксирует поздние остатки."),
    "tub": ("Бадья и руда", "Вместимость, цапфы, подвес и способ разгрузки требуют местного документа или изображения."),
}
CAPTIONS = ["Вид сбоку", "Вид с торца", "Вид сверху", "Аксонометрия"]


def decode(encoded):
    return Image.open(BytesIO(b64decode(encoded))).convert("RGB")


def plate(key, encoded):
    images=[decode(value) for value in encoded]
    title,description=ASSETS.get(key, ("Перегрузка руды в Storgrundet", "Баржа у причала · подъём наполненной бадьи · вагон на пути к домне. Расстояния и размеры условны."))
    canvas=Image.new("RGB",(1568,1032 if key!="scene" else 951),PAPER)
    pen=ImageDraw.Draw(canvas)
    pen.text((35,19),"HYTTGÅRDENS ACADEMY    /    STORGRUNDET",font=font("segoeuib.ttf",20),fill=MUTED)
    pen.text((32,49),title,font=font("georgia.ttf",45),fill=INK)
    pen.text((36,117),description,font=font("segoeui.ttf",21),fill=INK)
    pen.line((35,159,1533,159),fill="#b1bab0",width=2)
    if key=="scene":
        canvas.paste(images[3],(34,171))
    else:
        for i,im in enumerate(images):
            x=40+(i%2)*770
            y=178+(i//2)*404
            pen.text((x+12,y),CAPTIONS[i],font=font("segoeuib.ttf",21),fill=MUTED)
            canvas.paste(im,(x+8,y+30))
        pen.line((788,169,788,983),fill="#c9cec4",width=1)
    footer=("Три ортогональные проекции в общем масштабе · аксонометрия вписана отдельно." if key!="scene" else "Сборка из тех же объектов, что и на видовых листах.")
    pen.text((36,canvas.height-38),footer,font=font("segoeui.ttf",18),fill=MUTED)
    canvas.save(OUT/(key+".png"),optimize=True)


def main():
    with TemporaryDirectory() as temp_dir, sync_playwright() as pw:
        page_path=Path(temp_dir)/"viewer.html"
        html=(PROTOTYPE/"index.html").read_text("utf-8")
        html=html.replace('href="academy.css"',f'href="{(PROTOTYPE/"academy.css").as_uri()}"')
        html=html.replace('src="vendor/three.min.js"',f'src="{(PROTOTYPE/"vendor/three.min.js").as_uri()}"')
        page_path.write_text(html,encoding="utf-8")
        (page_path.parent/"harbour.js").write_text(setup_source(),encoding="utf-8")
        browser=pw.chromium.launch(channel="chrome",args=["--use-angle=swiftshader","--enable-unsafe-swiftshader"])
        page=browser.new_page(viewport={"width":1100,"height":800})
        errors=[]
        page.on("pageerror",lambda e: errors.append(str(e)))
        page.goto(page_path.as_uri())
        for key in [*ASSETS, "scene"]:
            plate(key,page.evaluate("key=>window.sheetViews(key)",key))
            print(key,flush=True)
        assert not errors,errors
        browser.close()


if __name__=="__main__":
    main()

