from __future__ import annotations

import json
import re
import sys
from pathlib import Path
from xml.etree import ElementTree as ET

ROOT = Path(__file__).resolve().parent
INPUT = ROOT / "34-svg-relief-input.svg"
OUTPUT = ROOT / "34-svg-relief-output.stl"
REPORT = ROOT / "34-svg-relief-verification.json"
HEIGHT = 3.0

root = ET.parse(INPUT).getroot()
rect = root.find("{http://www.w3.org/2000/svg}rect")
if rect is None:
    raise SystemExit("controlled fixture requires one SVG rect")
x, y, width, depth = (float(rect.attrib[name]) for name in ("x", "y", "width", "height"))
vertices = [(x, y, 0), (x + width, y, 0), (x + width, y + depth, 0), (x, y + depth, 0), (x, y, HEIGHT), (x + width, y, HEIGHT), (x + width, y + depth, HEIGHT), (x, y + depth, HEIGHT)]
triangles = [(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)]
lines = ["solid svg_relief_fixture"]
for triangle in triangles:
    lines.extend(["  facet normal 0 0 0", "    outer loop"])
    lines.extend(f"      vertex {vertices[index][0]:g} {vertices[index][1]:g} {vertices[index][2]:g}" for index in triangle)
    lines.extend(["    endloop", "  endfacet"])
lines.append("endsolid svg_relief_fixture")
OUTPUT.write_text("\n".join(lines) + "\n", encoding="ascii")
parsed = [tuple(map(float, match)) for match in re.findall(r"^\s*vertex\s+(-?\d+(?:\.\d+)?)\s+(-?\d+(?:\.\d+)?)\s+(-?\d+(?:\.\d+)?)$", OUTPUT.read_text(encoding="ascii"), re.MULTILINE)]
minimum = [min(point[axis] for point in parsed) for axis in range(3)]
maximum = [max(point[axis] for point in parsed) for axis in range(3)]
dimensions = [maximum[i] - minimum[i] for i in range(3)]
report = {"schemaVersion": 1, "checkedOn": "2026-09-06", "method": "Parsed the single rectangle in the original SVG, extruded it 3 mm into a closed 12-facet ASCII STL, and reparsed all output vertices. The script intentionally supports only this controlled rectangle fixture.", "input": INPUT.name, "output": OUTPUT.name, "result": {"svgRect": {"x": x, "y": y, "width": width, "height": depth}, "extrusionHeight": HEIGHT, "facetCount": len(triangles), "outputDimensions": dimensions}, "pass": len(parsed) == 36 and dimensions == [30.0, 10.0, 3.0]}
REPORT.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
print(json.dumps(report, indent=2))
sys.exit(0 if report["pass"] else 1)
