"""make_bracket.py - build a parametric L-bracket in FreeCAD (headless), check it, and draw it.

Run:  OUT=out freecadcmd make_bracket.py
Optional overrides via env: THICK, LENGTH, HEIGHT, WIDTH, HOLE_D, BORE_D, FILLET_R
Outputs in $OUT: bracket.FCStd, bracket.step, bracket.stl, bracket_drawing.svg,
bracket_drawing.dxf, report.json
"""
import os, json, math
import FreeCAD as App
import Part, Sketcher, TechDraw, Mesh

OUT = os.path.abspath(os.environ.get("OUT", "out"))
os.makedirs(OUT, exist_ok=True)
V = App.Vector

# ---------- 1. parameters live in a spreadsheet so a person (or the agent) edits one place
P = dict(Length=80.0, Height=50.0, Width=40.0, Thick=8.0, HoleD=6.6, BoreD=10.0,
         HoleInset=12.0, FilletR=4.0)
for k, env in [("Thick","THICK"),("Length","LENGTH"),("Height","HEIGHT"),("Width","WIDTH"),
               ("HoleD","HOLE_D"),("BoreD","BORE_D"),("FilletR","FILLET_R")]:
    if os.environ.get(env): P[k] = float(os.environ[env])

doc = App.newDocument("Bracket")
ss = doc.addObject("Spreadsheet::Sheet", "Params")
for i, (k, v) in enumerate(P.items(), start=1):
    ss.set(f"A{i}", k); ss.set(f"B{i}", f"{v}"); ss.setAlias(f"B{i}", k)
doc.recompute()

# ---------- 2. 2D: fully constrained L-profile sketch on the XZ plane, inside corner filleted in the sketch.
# The fillet lives in 2D on purpose: a 3D PartDesign Fillet references an edge by its topological name, and that
# reference broke ("Invalid edge link") as soon as a parameter edit re-generated the edges (seen in FreeCAD 1.1.4).
body = doc.addObject("PartDesign::Body", "Body")
xz = [f for f in body.Origin.OriginFeatures if f.Role == "XZ_Plane"][0]
sk = body.newObject("Sketcher::SketchObject", "Profile")
sk.AttachmentSupport = [(xz, "")]; sk.MapMode = "FlatFace"
L, H, T, R = P["Length"], P["Height"], P["Thick"], P["FilletR"]
seg = Part.LineSegment
sk.addGeometry(seg(V(0,0,0), V(L,0,0)), False)                 # 0 underside
sk.addGeometry(seg(V(L,0,0), V(L,T,0)), False)                 # 1 base end
sk.addGeometry(seg(V(L,T,0), V(T+R,T,0)), False)               # 2 base top
sk.addGeometry(Part.ArcOfCircle(Part.Circle(V(T+R,T+R,0), V(0,0,1), R), math.pi, 1.5*math.pi), False)  # 3 fillet
sk.addGeometry(seg(V(T,T+R,0), V(T,H,0)), False)               # 4 upright inner face
sk.addGeometry(seg(V(T,H,0), V(0,H,0)), False)                 # 5 upright top
sk.addGeometry(seg(V(0,H,0), V(0,0,0)), False)                 # 6 back face
C = Sketcher.Constraint
for a, b in [(0,1),(1,2),(4,5),(5,6),(6,0)]:
    sk.addConstraint(C("Coincident", a, 2, b, 1))
sk.addConstraint(C("Tangent", 2, 2, 3, 2))                     # base top -> fillet end
sk.addConstraint(C("Tangent", 3, 1, 4, 1))                     # fillet start -> upright face
for i in (0, 2, 5): sk.addConstraint(C("Horizontal", i))
for i in (1, 4, 6): sk.addConstraint(C("Vertical", i))
sk.addConstraint(C("Coincident", 0, 1, -1, 1))                 # corner on the origin
for expr, con in [("Params.Length", C("DistanceX", 0, 1, 0, 2, L)),
                  ("Params.Thick",  C("DistanceY", 1, 1, 1, 2, T)),
                  ("Params.Height", C("DistanceY", 6, 2, 6, 1, H)),
                  ("Params.Thick",  C("DistanceX", 5, 2, 5, 1, T)),
                  ("Params.FilletR", C("Radius", 3, R))]:
    sk.setExpression(f"Constraints[{sk.addConstraint(con)}]", expr)
doc.recompute()
dof = sk.solve()   # 0 = solved

# ---------- 3. 3D: pad symmetric about XZ, then cut holes with parametric cylinders
pad = body.newObject("PartDesign::Pad", "Pad")
pad.Profile = sk; pad.SideType = "Symmetric"
pad.setExpression("Length", "Params.Width")
doc.recompute()
tip = pad


W = P["Width"]
# every dimension of the cutters is an expression on the spreadsheet, so one edit there re-drives the whole part
hole_xy = [("Params.Length - Params.HoleInset", "-Params.Width / 4"),
           ("Params.Length - Params.HoleInset", "Params.Width / 4"),
           ("Params.Thick + Params.FilletR + Params.HoleInset", "0")]
holes = []
for n, (ex, ey) in enumerate(hole_xy):
    c = body.newObject("PartDesign::SubtractiveCylinder", f"BaseHole{n+1}")
    c.setExpression("Radius", "Params.HoleD / 2")
    c.setExpression("Height", "Params.Thick + 2")
    c.setExpression(".Placement.Base.x", ex)
    c.setExpression(".Placement.Base.y", ey)
    c.setExpression(".Placement.Base.z", "-1")
    holes.append(c)
bore = body.newObject("PartDesign::SubtractiveCylinder", "UprightBore")
bore.Placement = App.Placement(V(-1, 0, (H+T)/2), App.Rotation(V(0,1,0), 90))
bore.setExpression("Radius", "Params.BoreD / 2")
bore.setExpression("Height", "Params.Thick + 2")
bore.setExpression(".Placement.Base.z", "(Params.Height + Params.Thick) / 2")
doc.recompute()
shape = body.Shape

# ---------- 4. self-checks
def expected_volume():
    v = L*T*W + (H-T)*T*W                       # L-profile prism
    r = P["FilletR"]; v += (r*r - math.pi*r*r/4)*W  # fillet adds material
    v -= 3*math.pi*(P["HoleD"]/2)**2*T            # base holes
    v -= math.pi*(P["BoreD"]/2)**2*T              # upright bore
    return v
bb = shape.BoundBox
checks = {
  "sketch_solved": dof == 0,
  "sketch_fully_constrained": sk.FullyConstrained if hasattr(sk, "FullyConstrained") else None,
  "no_recompute_errors": not [o.Name for o in doc.Objects if {"Invalid", "Error"} & set(o.State)],
  "shape_valid": shape.isValid(),
  "one_solid": len(shape.Solids) == 1,
  "bbox_mm": [round(bb.XLength,3), round(bb.YLength,3), round(bb.ZLength,3)],
  "bbox_ok": abs(bb.XLength-L)<1e-3 and abs(bb.YLength-W)<1e-3 and abs(bb.ZLength-H)<1e-3,
  "volume_mm3": round(shape.Volume, 3),
  "expected_volume_mm3": round(expected_volume(), 3),
  "hole_faces": sum(1 for f in shape.Faces if f.Surface.__class__.__name__ == "Cylinder" and abs(f.Surface.Radius - P["HoleD"]/2) < 1e-6),
}
checks["volume_ok"] = abs(checks["volume_mm3"] - checks["expected_volume_mm3"]) < 1e-3 * checks["expected_volume_mm3"]
checks["mass_g_aluminium_6061"] = round(shape.Volume * 2.70e-3, 2)

# ---------- 5. 3D files
fcstd = os.path.join(OUT, "bracket.FCStd")
step = os.path.join(OUT, "bracket.step")
stl = os.path.join(OUT, "bracket.stl")
Part.export([body], step)
mesh = Mesh.Mesh(shape.tessellate(0.05)); mesh.write(stl)
back = Part.read(step)   # round-trip: re-read STEP and compare
checks["step_roundtrip_volume_mm3"] = round(back.Volume, 3)
checks["step_roundtrip_ok"] = abs(back.Volume - shape.Volume) < 1e-6 * shape.Volume + 1e-3
checks["stl_triangles"] = mesh.CountFacets
checks["stl_closed"] = mesh.isSolid()

# ---------- 6. 2D drawing: a TechDraw page (opens in the FreeCAD GUI) ...
tpl_dir = os.path.join(App.getResourceDir(), "Mod", "TechDraw", "Templates", "ISO")
page = doc.addObject("TechDraw::DrawPage", "Drawing")
tpl = doc.addObject("TechDraw::DrawSVGTemplate", "Template")
tpl.Template = os.path.join(tpl_dir, "A4_Landscape_TD.svg")
page.Template = tpl
views = {}
for name, d, xd, (px, py) in [("Front", V(0,-1,0), V(1,0,0), (75, 92)),
                              ("Top",   V(0,0,1),  V(1,0,0), (75, 166)),
                              ("Right", V(1,0,0),  V(0,1,0), (165, 92)),
                              ("Iso",   V(1,-1,1), V(1,1,0), (240, 125))]:
    v = doc.addObject("TechDraw::DrawViewPart", name)
    page.addView(v)
    v.Source = [body]; v.Direction = d; v.XDirection = xd
    v.Scale = 1.0; v.X = px; v.Y = py
    if name != 'Iso': v.HardHidden = True
    views[name] = v
doc.recompute()
# dimensions on the front view, located by geometry (projected 2D coordinates)
def dims_for_front(view):
    made = []
    try:
        made.append(TechDraw.makeDistanceDim(view, "DistanceX", V(0,0,0), V(L,0,0)))
        made.append(TechDraw.makeDistanceDim(view, "DistanceY", V(0,0,0), V(0,H,0)))
        made.append(TechDraw.makeDistanceDim(view, "DistanceY", V(L,0,0), V(L,T,0)))
    except Exception as e:
        checks["techdraw_dim_error"] = str(e)
    return made
dims_for_front(views["Front"])
doc.recompute()
tf = tpl.EditableTexts
for key in list(tf.keys()):
    lk = key.lower()
    if "title" in lk and "sub" not in lk: tf[key] = "L-bracket, parametric"
    elif "author" in lk or "drawn" in lk or "designed" in lk: tf[key] = "cad-agent (FreeCAD headless)"
    elif "scale" in lk: tf[key] = "1:1"
    elif "material" in lk: tf[key] = "AlMg1SiCu (6061)"
tpl.EditableTexts = tf
doc.recompute()
doc.saveAs(fcstd)

dxf = os.path.join(OUT, "bracket_drawing.dxf")
try:
    TechDraw.writeDXFPage(page, dxf); checks["dxf_written"] = os.path.getsize(dxf) > 0
except Exception as e:
    checks["dxf_written"] = False; checks["dxf_error"] = str(e)

# ---------- ... and a standalone SVG sheet (no GUI needed to render it). Third-angle projection.
sheet_w, sheet_h = 297, 210
half_h = {"Front": H/2, "Top": W/2, "Right": H/2, "Iso": 46}
parts = []
lab_gap = {"Front": 18, "Top": 9, "Right": 9, "Iso": 9}
for name, v in views.items():
    try:
        g = TechDraw.viewPartAsSvg(v).replace('stroke-width="0.35"', 'stroke-width="0.25" stroke-dasharray="1.5,0.8"').replace('stroke-width="0.7"', 'stroke-width="0.5"')
        parts.append(f'<g transform="translate({v.X.Value},{sheet_h - v.Y.Value})">{g}'
                     f'<text x="0" y="{half_h[name] + lab_gap[name]}" class="lbl">{name.upper()}</text></g>')
    except Exception as e:
        checks.setdefault("svg_view_errors", {})[name] = str(e)

def hdim(x1, x2, y, off, label):
    """horizontal dimension between x1..x2 measured at edge height y, line placed at y+off"""
    yy, s = y + off, (1 if off > 0 else -1)
    return (f'<line x1="{x1}" y1="{y + s}" x2="{x1}" y2="{yy + s}" class="d"/>'
            f'<line x1="{x2}" y1="{y + s}" x2="{x2}" y2="{yy + s}" class="d"/>'
            f'<line x1="{x1}" y1="{yy}" x2="{x2}" y2="{yy}" class="d" marker-start="url(#a)" marker-end="url(#a)"/>'
            f'<text x="{(x1 + x2) / 2}" y="{yy - 1}" class="t">{label}</text>')
def vdim(y1, y2, x, off, label, text_side=None):
    """vertical dimension between y1..y2 measured at edge x, line placed at x+off"""
    xx, s = x + off, (1 if off > 0 else -1)
    out = (f'<line x1="{x + s}" y1="{y1}" x2="{xx + s}" y2="{y1}" class="d"/>'
           f'<line x1="{x + s}" y1="{y2}" x2="{xx + s}" y2="{y2}" class="d"/>'
           f'<line x1="{xx}" y1="{y1}" x2="{xx}" y2="{y2}" class="d" marker-start="url(#a)" marker-end="url(#a)"/>')
    ym = (y1 + y2) / 2
    anc = 'start' if s > 0 else 'end'
    if text_side:   # short dimension: horizontal text beside the line
        out += f'<text x="{xx + 2 * s}" y="{ym + 1}" class="t" style="font-size:3px;font-family:sans-serif;text-anchor:{anc}">{label}</text>'
    else:
        out += f'<text x="{xx - 1.2}" y="{ym}" class="t" transform="rotate(-90 {xx - 1.2} {ym})">{label}</text>'
    return out

F, Tp = views["Front"], views["Top"]
# front view: model (x,z) -> sheet (fx + x - L/2, fy - (z - H/2)); TechDraw centres a view on its bounding box
fx, fy = F.X.Value, sheet_h - F.Y.Value
ox, oz = fx - L/2, fy + H/2
dims = (hdim(ox, ox + L, oz, 9, f"{L:g}") +
        vdim(oz, oz - H, ox, -9, f"{H:g}") +
        vdim(oz, oz - T, ox + L, 6, f"{T:g}", text_side=True) +
        hdim(ox, ox + T, oz - H, -6, f"{T:g}"))
# top view: model (x,y) -> sheet (tx + x - L/2, ty - y)
tx, ty = Tp.X.Value, sheet_h - Tp.Y.Value
hx = L - P["HoleInset"]
dims += (vdim(ty + W/2, ty - W/2, tx - L/2, -9, f"{W:g}") +
         hdim(tx - L/2 + hx, tx + L/2, ty - W/2, -6, f"{P['HoleInset']:g}") +
         vdim(ty + W/4, ty - W/4, tx + L/2, 7, f"{W/2:g}", text_side=True))
for (hxm, hym) in [(L - P['HoleInset'], -W/4), (L - P['HoleInset'], W/4), (T + P['FilletR'] + P['HoleInset'], 0)]:
    cx, cy = tx + hxm - L/2, ty - hym
    dims += (f'<line x1="{cx - 5}" y1="{cy}" x2="{tx + L/2 + 9 if hym else cx + 5}" y2="{cy}" class="c"/>'
             f'<line x1="{cx}" y1="{cy - 5}" x2="{cx}" y2="{cy + 5 if hym > -1 else ty - W/2 - 7}" class="c"/>')
rx, ry = views['Right'].X.Value, sheet_h - views['Right'].Y.Value
bz = ry - ((H + T)/2 - H/2)
dims += (f'<line x1="{rx - 8}" y1="{bz}" x2="{rx + W/2 + 10}" y2="{bz}" class="c"/><line x1="{rx}" y1="{bz - 8}" x2="{rx}" y2="{bz + 8}" class="c"/>'
         + vdim(ry + H/2, bz, rx + W/2, 9, f"{(H + T)/2:g}")
         + f'<polyline points="{rx - 3.5},{bz - 3.5} {rx - 12},{ry - H/2 - 5} {rx - 16},{ry - H/2 - 5}" class="d"/>'
         + f'<text x="{rx - 17}" y="{ry - H/2 - 4}" class="t" style="font-size:3px;font-family:sans-serif;text-anchor:end">Ø{P["BoreD"]:g} THRU</text>')
lx, ly = tx - L/2 + hx, ty + W/4
dims += (f'<polyline points="{lx + 2.4},{ly + 2.4} {tx + L/2 + 4},{ty + W/2 + 6} {tx + L/2 + 8},{ty + W/2 + 6}" class="d"/>'
         f'<text x="{tx + L/2 + 9}" y="{ty + W/2 + 7}" class="t" style="font-size:3px;font-family:sans-serif;text-anchor:start">3x Ø{P["HoleD"]:g} THRU</text>')
note = (f'<text x="16" y="{sheet_h - 40}" class="n" style="font-size:2.8px;font-family:sans-serif;font-weight:bold">NOTES</text>'
        f'<text x="16" y="{sheet_h - 35}" class="n">1. Upright bore centred across width {W:g}, at {(H + T)/2:g} from underside.</text>'
        f'<text x="16" y="{sheet_h - 30}" class="n">2. Inside corner R{P["FilletR"]:g}. Third hole {T + P["FilletR"] + P["HoleInset"]:g} from back face.</text>'
        f'<text x="16" y="{sheet_h - 25}" class="n">3. Third-angle projection. Dimensions in mm. General tol. ISO 2768-m.</text>'
        f'<text x="16" y="{sheet_h - 20}" class="n">4. Volume {shape.Volume:.0f} mm³, mass {shape.Volume * 2.70e-3:.1f} g (6061).</text>')
title = (f'<rect x="10" y="10" width="{sheet_w - 20}" height="{sheet_h - 20}" fill="none" stroke="#000" stroke-width="0.5"/>'
         f'<rect x="{sheet_w - 110}" y="{sheet_h - 30}" width="100" height="20" fill="none" stroke="#000" stroke-width="0.35"/>'
         f'<text x="{sheet_w - 107}" y="{sheet_h - 22}" font-size="5" font-family="sans-serif">L-BRACKET  (parametric)</text>'
         f'<text x="{sheet_w - 107}" y="{sheet_h - 14}" font-size="3" font-family="sans-serif">Scale 1:1 · mm · 6061-T6 · FreeCAD {".".join(App.Version()[:3])} headless</text>')
svg = (f'<svg xmlns="http://www.w3.org/2000/svg" width="{sheet_w}mm" height="{sheet_h}mm" viewBox="0 0 {sheet_w} {sheet_h}">'
       '<defs><marker id="a" viewBox="0 0 6 6" refX="3" refY="3" markerWidth="4" markerHeight="4" orient="auto-start-reverse">'
       '<path d="M0,0 L6,3 L0,6 z"/></marker><style>.d{stroke:#000;stroke-width:0.18;fill:none}'
       '.t{font-size:3px;font-family:sans-serif;text-anchor:middle}.lbl{font-size:3.2px;font-family:sans-serif;text-anchor:middle;font-weight:bold}'
       '.n{font-size:3px;font-family:sans-serif}.c{stroke:#000;stroke-width:0.13;stroke-dasharray:3,0.8,0.6,0.8;fill:none}</style></defs>'
       '<rect width="100%" height="100%" fill="#fff"/>' + title + "".join(parts) + dims + note + '</svg>')
svgp = os.path.join(OUT, "bracket_drawing.svg")
open(svgp, "w", encoding="utf-8").write(svg)

checks["svg_views"] = len(parts)

checks["parameters"] = P
checks["all_ok"] = all(checks[k] for k in ("sketch_solved","no_recompute_errors","shape_valid","one_solid",
                                           "bbox_ok","volume_ok","step_roundtrip_ok","stl_closed")) and checks["hole_faces"] == 3
json.dump(checks, open(os.path.join(OUT, "report.json"), "w", encoding="utf-8"), indent=2)
print(json.dumps(checks, indent=2))

