"""Omega (hat) sheet-metal bracket, 1.5 mm steel, 4 bends 90 deg.
Built by sweeping a t x L rectangle along the bent centerline -> true concentric bends.
Flat pattern computed with K-factor (DIN 6935 style: BA = angle * (R + K*t)).
Run: venv python omega_bracket.py   (outputs next to this file)
"""
import math, json, os
import cadquery as cq
import ezdxf

HERE = os.path.dirname(os.path.abspath(__file__))

# ---- parameters (mm) ----
T = 1.5          # sheet thickness
R = 1.5          # inner bend radius
K = 0.42         # K-factor (R/t = 1.0, cold rolled steel, air bending)
L = 60.0         # part depth (along bend lines)
FOOT = 22.0      # foot length (outer edge to wall outer face)
H = 32.0         # height (outer, base underside to top outer)
TOP = 40.0       # top width (outer)
FOOT_HOLE = 6.6  # M6 clearance
TOP_HOLE = 8.5   # M8 clearance
SLOT = (16.0, 6.0)  # slot in each wall (length along L, width)

# centerline points (XZ plane), sheet centerline sits t/2 inside the outer faces
h = T / 2
xw = TOP / 2 - h                 # wall centerline x
pts = [(-(TOP / 2 + FOOT - T) , h),  # foot outer end (foot outer face = wall outer face + FOOT)
       (-xw, h), (-xw, H - h), (xw, H - h), (xw, h),
       ((TOP / 2 + FOOT - T), h)]
# NB: feet: foot top surface at z=t, underside at z=0
Rm = R + h  # centerline bend radius

def bent_centerline():
    w = cq.Wire.makePolygon([cq.Vector(x, 0, z) for x, z in pts])
    inner = w.Vertices()[1:-1]
    return w.fillet2D(Rm, inner) if hasattr(w, "fillet2D") else w.fillet(Rm, inner)

path = bent_centerline()
start = cq.Vector(*[pts[0][0], 0, pts[0][1]])
# profile: rectangle T (z) x L (y) in plane normal to X at path start
prof = cq.Workplane(cq.Plane(origin=start, xDir=(0, 1, 0), normal=(1, 0, 0))).rect(L, T)
body = prof.sweep(cq.Workplane().add(path), transition="right")

# ---- holes ----
foot_cx = TOP / 2 + (FOOT - T) / 2 + R / 2  # middle of flat foot region approx
foot_cx = (xw + Rm + (TOP / 2 + FOOT - T)) / 2
for sx in (-1, 1):
    for y in (-L / 4, L / 4):
        body = body.cut(cq.Workplane("XY").circle(FOOT_HOLE / 2).extrude(10).translate((sx * foot_cx, y, -5)))
for y in (-L / 4, L / 4):
    body = body.cut(cq.Workplane("XY").circle(TOP_HOLE / 2).extrude(10).translate((0, y, H - 5)))
for sx in (-1, 1):
    slot = (cq.Workplane("YZ").slot2D(SLOT[0], SLOT[1]).extrude(10)
            .translate((sx * xw - 5, 0, H / 2)))
    body = body.cut(slot)

solid = body.val()
cq.exporters.export(body, os.path.join(HERE, "omega_bracket.step"))
cq.exporters.export(body, os.path.join(HERE, "omega_bracket.stl"), tolerance=0.02, angularTolerance=0.1)

# ---- flat pattern (analytic) ----
segs = []
for (x0, z0), (x1, z1) in zip(pts[:-1], pts[1:]):
    segs.append(math.hypot(x1 - x0, z1 - z0))
# straight (flat) parts: each internal vertex consumes Rm (tangent length for 90 deg) on both sides
flat_parts = []
for i, s in enumerate(segs):
    cut = 0.0
    if i > 0: cut += Rm
    if i < len(segs) - 1: cut += Rm
    flat_parts.append(s - cut)
nb = len(pts) - 2
BA = (math.pi / 2) * (R + K * T)
flat_len = sum(flat_parts) + nb * BA
bb = solid.BoundingBox()
res = {
    "thickness": T, "inner_R": R, "K": K, "bends": nb,
    "bend_allowance_mm": round(BA, 4),
    "flat_straights_mm": [round(v, 3) for v in flat_parts],
    "flat_length_mm": round(flat_len, 3),
    "bbox_mm": [round(bb.xlen, 3), round(bb.ylen, 3), round(bb.zlen, 3)],
    "volume_mm3": round(solid.Volume(), 2),
    "volume_check_flat_mm3": None,
    "valid": solid.isValid(),
}

# ---- DXF flat ----
doc = ezdxf.new("R2010", setup=True)
doc.layers.add("CUT", color=7); doc.layers.add("BEND", color=1, linetype="DASHED"); doc.layers.add("TEXT", color=3)
msp = doc.modelspace()
msp.add_lwpolyline([(0, 0), (flat_len, 0), (flat_len, L), (0, L)], close=True, dxfattribs={"layer": "CUT"})
# positions along the flat
s = 0.0
marks = []  # (start, end) of each bend zone
for i, fp in enumerate(flat_parts):
    seg_start = s
    s += fp
    if i < nb:
        marks.append((s, s + BA)); s += BA
# features: map from centerline
def s_of_foot_hole(side):
    # left foot: distance from outer end = foot_cx distance from foot outer end
    d = (TOP / 2 + FOOT - T) - foot_cx
    return d if side < 0 else flat_len - d
holes = []
for side in (-1, 1):
    for y in (L / 4, 3 * L / 4):
        holes.append((s_of_foot_hole(side), y, FOOT_HOLE))
top_mid = marks[1][1] + flat_parts[2] / 2
for y in (L / 4, 3 * L / 4):
    holes.append((top_mid, y, TOP_HOLE))
for x, y, d in holes:
    msp.add_circle((x, y), d / 2, dxfattribs={"layer": "CUT"})
# wall slots: wall flat = flat_parts[1] and [3]; slot centred at z=H/2 -> along wall
for wi, (a, b) in ((1, marks[0]), (3, marks[2])):
    wall_start = b
    zc_from_bottom = H / 2 - (h + Rm)  # distance along wall from end of lower bend
    if wi == 3:  # right wall runs downward in flat order
        wall_start = marks[2][1]
        zc = wall_start + (flat_parts[3] - zc_from_bottom)
    else:
        zc = wall_start + zc_from_bottom
    # slot: long axis along L (y), width along flat x
    sl, sw = SLOT
    yc = L / 2
    r = sw / 2
    msp.add_line((zc - r, yc - sl / 2 + r), (zc - r, yc + sl / 2 - r), dxfattribs={"layer": "CUT"})
    msp.add_line((zc + r, yc - sl / 2 + r), (zc + r, yc + sl / 2 - r), dxfattribs={"layer": "CUT"})
    msp.add_arc((zc, yc + sl / 2 - r), r, 0, 180, dxfattribs={"layer": "CUT"})
    msp.add_arc((zc, yc - sl / 2 + r), r, 180, 360, dxfattribs={"layer": "CUT"})
dirs = ["UP", "UP", "UP", "UP"]
labels = ["BEND 90 DOWN", "BEND 90 UP", "BEND 90 UP", "BEND 90 DOWN"]
for (a, b), lab in zip(marks, labels):
    c = (a + b) / 2
    msp.add_line((c, -3), (c, L + 3), dxfattribs={"layer": "BEND"})
    msp.add_text(f"{lab} R{R}", height=2.2, rotation=90, dxfattribs={"layer": "TEXT"}).set_placement((c - 1, L + 5))
dimstyle = {"dimtxt": 3.0, "dimasz": 2.5, "dimlfac": 1.0, "dimdec": 2}
d = msp.add_linear_dim(base=(0, -10), p1=(0, 0), p2=(flat_len, 0), override=dimstyle); d.render()
d = msp.add_linear_dim(base=(-10, 0), p1=(0, 0), p2=(0, L), angle=90, override=dimstyle); d.render()
msp.add_text(f"FLAT S={T} K={K} BA={BA:.3f}  L_flat={flat_len:.2f}", height=3,
             dxfattribs={"layer": "TEXT"}).set_placement((0, -22))
doc.saveas(os.path.join(HERE, "omega_bracket_flat.dxf"))
res["flat_volume_mm3_minus_holes_approx"] = None
res["marks"] = [[round(a, 3), round(b, 3)] for a, b in marks]
res["holes_flat"] = [[round(x, 3), round(y, 3), dd] for x, y, dd in holes]
json.dump(res, open(os.path.join(HERE, "omega_bracket.json"), "w"), indent=1)
print(json.dumps(res, indent=1))
