import json, html

scene = json.load(open("/home/min/hermes_workspace/demo_review/ai_harness_final.excalidraw"))
els = scene["elements"]

# index bound texts by containerId
bound = {}
standalone = []
for e in els:
    if e["type"] == "text" and e.get("containerId"):
        bound[e["containerId"]] = e
    elif e["type"] == "text":
        standalone.append(e)

def esc(s): return html.escape(s)

svg = []
max_y = max((e["y"] + sum(e["points"], [0])[1] if "points" in e else e["y"] + e.get("height", 40) for e in els), default=780)
max_x = max((e["x"] + sum(e["points"], [0])[0] if "points" in e else e["x"] + e.get("width", 200) for e in els), default=1520)
W, H = int(max_x + 60), int(max_y + 60)
svg.append(f'<svg xmlns="http://www.w3.org/2000/svg" width="{W}" height="{H}" viewBox="0 0 {W} {H}">')
svg.append(f'<rect width="{W}" height="{H}" fill="#ffffff"/>')

for e in els:
    t = e["type"]
    if t == "text" and e.get("containerId"):
        continue  # handled with its container
    if t == "rectangle":
        x, y, w, h = e["x"], e["y"], e["width"], e["height"]
        fill = e.get("backgroundColor", "transparent")
        if fill == "transparent":
            fattr = 'fill="none"'
        else:
            fattr = f'fill="{fill}"'
        svg.append(f'<rect x="{x}" y="{y}" width="{w}" height="{h}" rx="10" {fattr} stroke="#1e1e1e" stroke-width="2"/>')
        bt = bound.get(e["id"])
        if bt:
            lines = bt["text"].split("\n")
            fs = bt["fontSize"]
            lh = fs * 1.35
            total = lh * len(lines)
            ty = y + h/2 - total/2 + fs
            # title-style single-line texts get centered; bullet blocks left-aligned
            if len(lines) == 1:
                svg.append(f'<text x="{x+w/2}" y="{ty:.0f}" font-size="{fs}" font-family="sans-serif" fill="#1e1e1e" text-anchor="middle">{esc(lines[0])}</text>')
            else:
                for i, ln in enumerate(lines):
                    svg.append(f'<text x="{x+30}" y="{ty + i*lh:.0f}" font-size="{fs}" font-family="sans-serif" fill="#1e1e1e">{esc(ln)}</text>')
    elif t == "arrow":
        pts = e["points"]
        x0, y0 = e["x"], e["y"]
        path = "M " + " L ".join(f"{x0+dx:.0f},{y0+dy:.0f}" for dx, dy in pts)
        dash = ' stroke-dasharray="8,6"' if e.get("strokeStyle") == "dashed" else ""
        color = e.get("strokeColor", "#1e1e1e")
        svg.append(f'<path d="{path}" fill="none" stroke="{color}" stroke-width="2"{dash} marker-end="url(#arr)"/>')
        bt = bound.get(e["id"])
        if bt:
            cx = sum(p[0] for p in pts) / len(pts)
            cy = sum(p[1] for p in pts) / len(pts)
            mx, my = x0 + cx, y0 + cy
            fs = bt["fontSize"]
            lines = bt["text"].split("\n")
            for i, ln in enumerate(lines):
                svg.append(f'<text x="{mx:.0f}" y="{my - 8 + i*fs*1.35:.0f}" font-size="{fs}" font-family="sans-serif" fill="{color}" text-anchor="middle" stroke="#ffffff" stroke-width="4" paint-order="stroke">{esc(ln)}</text>')
    elif t == "text":
        fs = e["fontSize"]
        lines = e["text"].split("\n")
        for i, ln in enumerate(lines):
            svg.append(f'<text x="{e["x"]}" y="{e["y"] + fs + i*fs*1.35:.0f}" font-size="{fs}" font-family="sans-serif" fill="#1e1e1e">{esc(ln)}</text>')

svg.append('<defs><marker id="arr" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="8" markerHeight="8" orient="auto-start-reverse"><path d="M 0 0 L 10 5 L 0 10 z" fill="context-stroke"/></marker></defs>')
svg.append('</svg>')

open("/home/min/hermes_workspace/demo_review/diagram_preview.svg", "w").write("\n".join(svg))
print("rendered diagram_preview.svg,", len("\n".join(svg)), "bytes")