"""Headless FreeCAD CAM: plate.step -> Job (6 mm endmill) -> PocketShape x2 + Profile -> G-code (linuxcnc post)."""
import os, sys, traceback
HERE = r"C:\rclone\cad_probe_20261108\storm\cnc"
import FreeCAD, Part, Path
from Path.Main import Job
import Path.Op.Profile as Profile
import Path.Op.PocketShape as PocketShape
import Path.Tool.Controller as TC

doc = FreeCAD.newDocument("plate_cam")
shape = Part.read(os.path.join(HERE, "plate.step"))
model = doc.addObject("Part::Feature", "Plate"); model.Shape = shape
doc.recompute()
job = Job.Create("Job", [model])
doc.recompute()
base = job.Model.Group[0]
print("job model:", base.Name, base.Shape.BoundBox)

# tool controller
tcs = job.Tools.Group
print("existing TCs:", [t.Label for t in tcs])
if not tcs:
    tc = TC.Create("TC: 6mm Endmill", assignViewProvider=False)
    job.Proxy.addToolController(tc)
tc = job.Tools.Group[0]
try:
    tc.Tool.Diameter = 6.0
except Exception as e:
    print("tool diameter set fail:", e)
tc.HorizFeed = "600 mm/min"; tc.VertFeed = "150 mm/min"; tc.HorizRapid = "3000 mm/min"; tc.SpindleSpeed = 12000; tc.Label = "TC: 6mm Endmill"
print("TC:", tc.Label, "D=", getattr(tc.Tool, "Diameter", "?"))

# find faces: pocket floors (horizontal faces below top, not bottom)
floors = []
for i, f in enumerate(base.Shape.Faces):
    if f.Surface.__class__.__name__ == "Plane":
        z0, z1 = f.BoundBox.ZMin, f.BoundBox.ZMax
        if abs(z1 - z0) < 1e-6 and 0.5 < z0 < 11.5:
            floors.append(("Face%d" % (i + 1), round(z0, 3), round(f.Area, 1)))
print("pocket floors:", floors)

ops = []
for name, z, a in floors:
    op = PocketShape.Create("Pocket_z%s" % str(z).replace(".", "_"))
    op.Base = [(base, [name])]
    op.StepOver = 45
    op.ToolController = tc
    for prop, val in (("StartDepth", "12 mm"), ("FinalDepth", "%s mm" % z), ("StepDown", "1.5 mm")):
        try: op.setExpression(prop, None)
        except Exception: pass
        setattr(op, prop, val)
    ops.append(op)
prof = Profile.Create("Profile_outer")
prof.ToolController = tc
for prop, val in (("StartDepth", "12 mm"), ("FinalDepth", "-0.5 mm"), ("StepDown", "2 mm")):
    try: prof.setExpression(prop, None)
    except Exception: pass
    setattr(prof, prop, val)
try:
    prof.Side = "Outside"; prof.processHoles = False; prof.processPerimeter = True
except Exception as e:
    print("profile prop:", e)
ops.append(prof)
doc.recompute()
for op in ops:
    cmds = op.Path.Commands if op.Path else []
    print(op.Label, "commands:", len(cmds), "state:", op.State if hasattr(op, "State") else "")

# post
out = os.path.join(HERE, "plate_freecad.nc")
try:
    from Path.Post.Processor import PostProcessorFactory
    pp = PostProcessorFactory.get_post_processor(job, "linuxcnc")
    gcode = pp.export()
    text = gcode[0][1] if isinstance(gcode, list) else gcode
    open(out, "w").write(text)
    print("post via factory ok")
except Exception:
    traceback.print_exc()
    import importlib
    post = importlib.import_module("Path.Post.scripts.linuxcnc_post")
    objs = [job.Stock] + list(job.Tools.Group) + ops
    post.export(ops, out, "--no-show-editor")
    print("post via legacy script ok")
doc.saveAs(os.path.join(HERE, "plate_cam.FCStd"))
print("written", out, os.path.getsize(out))
