#!/usr/bin/env python3
# Test stand-in for OpenSCAD: makes simple boxes so the tests run without OpenSCAD installed.
import sys, re, shutil, struct, os
a = sys.argv[1:]
if "--version" in a: print("OpenSCAD version 2026.09.01 (test stand-in)", file=sys.stderr); sys.exit(0)
if "--help" in a: print("--backend arg  3D rendering backend"); sys.exit(0)
out = a[a.index("-o")+1]; src = a[-1]
D = dict(x.split("=",1) for i,x in enumerate(a) if i and a[i-1]=="-D")
code = open(src).read()
if "syntax_error_here" in code: print("ERROR: Parser error in file model.scad, line 9: syntax error", file=sys.stderr); sys.exit(1)
if "// WARN" in code: print("WARNING: Mixing 2D and 3D objects is not supported in file model.scad, line 12", file=sys.stderr)
m = re.search(r'import\("([^"]+)"\)', code)
sys.path.insert(0, os.environ.get("KIDCAD_APP") or os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "app"))
import mesh, numpy as np
if m:
    tris = mesh.read_stl(os.path.join(os.path.dirname(src), m.group(1)))
    if "height" in code and "FOOT_X" in code:
        h=float(D.get("height", re.search(r"height = ([\d.]+)",code).group(1))); tris = tris*(h/100.0)
else:
    v = {k: float(v) for k, v in re.findall(r"^(\w+) = ([\d.]+);", code, re.M)}
    v.update({k: float(x) for k,x in D.items() if re.fullmatch(r"[\d.]+",x)})
    sx = v.get("size", 40); sz = v.get("height", 20)
    q = np.array([[0,0,0],[1,0,0],[1,1,0],[0,1,0],[0,0,1],[1,0,1],[1,1,1],[0,1,1]],float)*[sx,sx,sz]-[sx/2,sx/2,0]
    f=[(0,2,1),(0,3,2),(4,5,6),(4,6,7),(0,1,5),(0,5,4),(1,2,6),(1,6,5),(2,3,7),(2,7,6),(3,0,4),(3,4,7)]
    tris = np.array([[q[i] for i in t] for t in f], np.float32)
mesh.write_stl(out, tris)
