"""Inspectable, deterministic onboarding reference. Not an AI benchmark.

Review before executing through the installed application's macro mechanism.
Creates only a new reference document and refuses to overwrite its output.
"""
from pathlib import Path
import json
import FreeCAD as App

folder = Path.home() / "SynthCrew-Tutorial"
target = folder / "ReferenceBox.FCStd"
receipt = folder / "reference-kernel-check.json"
if target.exists() or receipt.exists():
    raise RuntimeError("Reference output already exists; preserve it or choose a new disposable folder.")
folder.mkdir(parents=True, exist_ok=True)
doc = App.newDocument("SynthCrewReference")
box = doc.addObject("Part::Box", "ReferenceBox")
box.Label = "Reference box — 60 × 40 × 6 mm"
box.Length = 60
box.Width = 40
box.Height = 6
doc.recompute()
shape = box.Shape
if shape.isNull() or not shape.isValid() or len(shape.Solids) != 1:
    raise RuntimeError("The reference did not produce one valid solid; no successful check is claimed.")
if abs(shape.Volume - 14400.0) > 0.001:
    raise RuntimeError("Unexpected reference volume; inspect the runtime and units.")
doc.saveAs(str(target))
# Reopen only this newly created document, so the receipt checks the saved file,
# not just the pre-save in-memory shape. Unrelated documents are not closed.
App.closeDocument(doc.Name)
doc = App.openDocument(str(target))
box = doc.getObject("ReferenceBox")
shape = box.Shape
if shape.isNull() or not shape.isValid() or len(shape.Solids) != 1 or abs(shape.Volume - 14400.0) > 0.001:
    raise RuntimeError("Saved reference did not pass the independent reopen check.")
receipt.write_text(json.dumps({
    "kind": "deterministic_reference_kernel_check",
    "ai_inference": False,
    "length_mm": float(box.Length.Value),
    "width_mm": float(box.Width.Value),
    "height_mm": float(box.Height.Value),
    "solid_count": len(shape.Solids),
    "valid": shape.isValid(),
    "reopened_from_saved_file": True,
    "volume_mm3": shape.Volume,
    "document": target.name,
    "runtime_version": list(App.Version()[:3]),
}, indent=2) + "\n", encoding="utf-8")
print("Reference saved. Inspect the document and reference-kernel-check.json in", folder)
