"""Bob Bot cost-down: actuator sizing, per-part print conversion, mass model, totals.
Writes /workspace/asimov-guide/costdown/data/*.json|csv. Derived from Menlo Asimov 1 (CERN-OHL-S-2.0)."""
import json, math, csv, os, sys
sys.path.insert(0, os.path.dirname(__file__))
from prices import P
OUT = "/workspace/asimov-guide/costdown/data"; os.makedirs(OUT, exist_ok=True)
G = json.load(open("/workspace/asimov-guide/build/guide-data.json"))
CAD = json.load(open("/workspace/asimov-guide/costdown/cad/out/actuator_cad.json"))
VOL = json.load(open("/workspace/asimov-guide/costdown/work/vol_all.json"))

# ---------------- materials (sources on page) ----------------
MAT = {
 "7075": dict(E=71.7e3, sy=503, rho=2.81, src="ASM Aerospace Specification Metals 7075-T6 datasheet"),
 "6063": dict(E=68.9e3, sy=145, rho=2.70, src="ASM MatWeb 6063-T5"),
 "316L": dict(E=193e3, rho=8.0, src="typical wrought 316L E~193 GPa; SLM density ~8.0 g/cm3"),
 "PAHT": dict(E=4120, sf=140.8, st=88.7, rho=1.06, src="Bambu Lab PAHT-CF data via listing (flexural modulus 4120 MPa, flexural strength 140.8 MPa, tensile 88.7 MPa, 1.06 g/cm3)"),
 "PETGCF": dict(rho=1.29, src="density proxy: Bambu PET-CF 1.29 g/cm3 (PETG-CF vendor gives none)"),
 "PA12MJF": dict(rho=1.01, src="HP MJF PA12 ~1.01 g/cm3"),
}
RATE = {"PAHT": 15.0, "PETGCF": 20.0}   # cm3/h deposited -- ASSUMPTION (0.6 mm nozzle, engineering profile)
FIL = {"PAHT": P["paht_cf"]["price"], "PETGCF": P["petg_cf"]["price"]}  # $/kg
SCRAP = 1.10  # +10 % supports/purge -- assumption

# ---------------- DIY actuator electrical model ----------------
KT0, R0 = 0.0919, 0.1886          # stock M6C12 150KV, BHL paper measured
KT, R = 2*KT0, 4*R0               # rewound at 2x turns, ~half copper area (same slot fill)
VBUS, IPK, PCU = 44.4, 20.0, 40.0 # 12S nominal; moteus-c1 peak phase current; copper-loss budget (assumption)
KE = KT/1.225                     # line-line peak back-EMF const (V s/rad) for sinusoidal drive
def act(size):
    p = dict(M=dict(ratio=15, eta=0.90, gear_peak=20.0, gear_cont=10.0),
             L=dict(ratio=20, eta=0.85, gear_peak=60.0, gear_cont=30.0))[size]
    n, eta = p["ratio"], p["eta"]
    t_motor_pk = KT*IPK*n*eta
    peak = min(p["gear_peak"], t_motor_pk)
    icont = math.sqrt(PCU/(1.5*R))
    cont = min(p["gear_cont"], KT*icont*n*eta)
    w0 = VBUS/KE/n
    def w_at(T):
        I = T/(KT*n*eta); return max(0.0, (VBUS - math.sqrt(3)*I*R)/KE/n)
    return dict(size=size, ratio=n, eta=eta, kt_motor=round(KT,4), r_phase=round(R,3), peak=round(peak,1),
                motor_limited_peak=round(t_motor_pk,1), cont=round(cont,1), i_cont=round(icont,2),
                i_at_peak=round(peak/(KT*n*eta),2), w_noload=round(w0,1), w_at_peak=round(w_at(peak),1),
                w_at_45=round(w_at(45),1) if size=="L" else None, w_at_20=round(w_at(20),1),
                armature=round(1.3e-4*n*n, 4))  # rotor J ~1.3e-4 kg m2 (thin-ring estimate) -> reflected

A = {s: act(s) for s in ("M", "L")}

# mass: printed parts (solid CAD volume x 0.8 effective fill x 1.06) + bought hardware (catalogue approx.)
def act_mass(s):
    v = CAD[s]["part_volumes_cm3"]
    printed = (2*v["cycloid_disk"] + v["front_housing"] + v["output_flange"] + v["eccentric_hub"] + v["motor_bell"] + v["rear_cover"]) * 0.8 * 1.06
    hw = dict(motor=257, output_bearing=85 if s=="M" else 130, ecc_bearings=2*(8 if s=="M" else 22),
              ring_pins=CAD[s]["N_pins"]*2.0, out_pins=CAD[s]["params"]["n_out"]*2.0, rollers=CAD[s]["params"]["n_out"]*1.2,
              moteus_c1=8.9, heat_spreader=0 if s=="M" else 15, fasteners_inserts=25, wiring=20)
    return round(printed, 0), hw, round(printed + sum(hw.values()), 0)
for s in A:
    pm, hw, tot = act_mass(s); A[s].update(printed_g=pm, hardware_g=hw, mass_g=tot, OD=CAD[s]["OD"], length=CAD[s]["length"])

# per-unit BOM
def unit_bom(s):
    nb = CAD[s]["N_pins"] + CAD[s]["params"]["n_out"]
    rows = [("m6c12", 1, 1), ("moteus_c1", 1, 1),
            ("b61811" if s=="M" else "b61814", 1, 1),
            ("b6803_10" if s=="M" else "b6805_10", 2, 10),
            ("b684_50", CAD[s]["params"]["n_out"], 50),
            ("dowel4x20_50", nb, 50),
            ("insert_m3_100", 22, 100),
            ("wire24", 1, 4),          # ~4 stators per lb (estimate; verify copper mass on teardown)
           ]
    if s == "L": rows.append(("c1_heat", 1, 1))
    out = []; tot = 0
    for k, q, pack in rows:
        unit = P[k]["price"]/pack
        c = unit*q; tot += c
        out.append(dict(key=k, item=P[k]["item"], qty=q, pack=pack, unit_cost=round(unit,3), cost=round(c,2), url=P[k]["url"], checked=P[k]["checked"]))
    pm = A[s]["printed_g"]
    # gear parts (disks, flange, hub) in PAHT-CF, housings in PAHT-CF too (heat near motor)
    fil = pm/1000*SCRAP*FIL["PAHT"]; tot += fil
    out.append(dict(key="filament", item=f"PAHT-CF filament {pm:.0f} g (+10 %)", qty=1, pack=1, unit_cost=round(fil,2), cost=round(fil,2), url=P["paht_cf"]["url"], checked=P["paht_cf"]["checked"]))
    hrs = sum(CAD[s]["part_volumes_cm3"].values())*0.8/RATE["PAHT"] + CAD[s]["part_volumes_cm3"]["cycloid_disk"]*0.8/RATE["PAHT"]
    return out, round(tot, 2), round(hrs, 1)
for s in A:
    b, t, h = unit_bom(s); A[s].update(bom=b, unit_cost=t, print_h=h)

# ---------------- joints ----------------
ROLE = {}
for a in G["actuators"]: ROLE[a["role"]] = a
L_J = ["hip_pitch", "hip_roll", "hip_yaw", "knee", "shoulder_pitch", "shoulder_roll", "shoulder_yaw"]
joints = []
RS = dict(RS03=dict(peak=60, rated=20, w0=20.4, mass=0.880, price=225.0, src="Seeed / RobStride spec 2025-06-26"),
          RS06=dict(peak=36, rated=11, w0=50.3, mass=0.621, price=210.0, src="Seeed / RobStride spec"),
          RS02=dict(peak=17, rated=6, w0=42.9, mass=0.405, price=145.0, src="Seeed / RobStride spec"))
ENC_MASS = {"EC-A4310-P2-36": .382, "EC-A4315-P2-36": .485, "EC-A6416-P2-25": .805, "EC-A5013-H17-100": .630, "EC-A3814-H14-107": .434}
ENC_PRICE = {"EC-A4310-P2-36": 700, "EC-A4315-P2-36": 750, "EC-A6416-P2-25": 925, "EC-A5013-H17-100": 1500, "EC-A3814-H14-107": 1375}
for a in G["actuators"]:
    r = a["role"]; base = r.replace("left_", "").replace("right_", "").replace("_joint", "")
    ankle = "ankle" in r
    size = "L" if (base in L_J or base == "waist_yaw") else "M"
    rs = "RS03" if base in ("hip_pitch", "hip_roll", "knee", "shoulder_pitch", "waist_yaw") else ("RS06" if base in ("hip_yaw", "shoulder_roll", "shoulder_yaw") else "RS02")
    cap = a["urdf_effort"]
    if ankle:  # motor-space requirement from joint caps via Menlo's RSU table (pitch 145.4/36 = 4.04x, roll 57.6/36 = 1.6x)
        cap = 40/4.04 if r.endswith("_A") else 17/1.6
    d = A[size]
    joints.append(dict(role=r, menlo_model=a["model"], enc_rated=float(a["rated"]), enc_peak=float(a["peak"]), enc_vel=float(a["vel"]),
        enc_armature=float(a["armature"]), urdf_cap=a["urdf_effort"], motor_space_req=round(cap,1),
        diy=f"DIY-{size}", diy_peak=d["peak"], diy_cont=d["cont"], diy_w0=d["w_noload"], diy_w_pk=d["w_at_peak"],
        margin_vs_cap=round(d["peak"]/cap, 2), rs_alt=rs, rs_peak=RS[rs]["peak"],
        enc_mass=ENC_MASS[a["model"]], diy_mass=d["mass_g"]/1000, enc_price=ENC_PRICE[a["model"]]))
json.dump(dict(actuators=A, joints=joints, rs=RS, motor=dict(kt0=KT0, r0=R0, kt=KT, r=R, vbus=VBUS, ipk=IPK, pcu=PCU)), open(f"{OUT}/actuators.json", "w"), indent=1)

# ---------------- per-part conversion ----------------
TUBE = {"500_05A", "500_06A", "500_08A", "500_09A", "600_05A", "600_06A", "600_08A", "600_09A"}
rows = []
for o in VOL:
    pid = o["part"].replace("ASV1_", ""); cls = o["cls"]; v = o["vol_cm3"]; teff = 20*v/o["area_cm2"]
    r = dict(part=o["part"], module=o["sub"], orig_process=cls, orig_vol_cm3=round(v,1), bbox_mm=o["bb"], est_vol=o.get("est", False))
    if cls == "ALU_7075":
        m0 = v*MAT["7075"]["rho"]
        if pid in TUBE:
            L = max(o["bb"]); tube_v = math.pi/4*(25**2-20**2)*L/1000
            pv = 0.8*v
            r.update(new="PAHT-CF end clamps + bought 6063-T5 tube 25x20", reinforcement="Al tube (bought)", printed_vol=round(pv,1),
                     new_mass_g=round(pv*1.06 + tube_v*2.70, 0), tube_mm=round(L), check="thigh/shin tube check (see stress table)", cad_change="replace plate with tube + 2 clamps (CAD: leg_link)")
        elif pid.endswith("_SS"):
            L = max(o["bb"])
            r.update(new="bought M6 stainless threaded rod cut to length", reinforcement="steel rod (bought)", printed_vol=0.0,
                     new_mass_g=round(math.pi/4*36*L/1000*7.9, 0), check="axial only; M6 A2 stress area 20.1 mm2", cad_change="rod ends thread onto M6")
        else:
            k = 2.6
            pv = v*k
            r.update(new="PAHT-CF, walls/plates thickened x2.6", reinforcement="M3 heat-set inserts; steel dowels at bores", printed_vol=round(pv,1), new_mass_g=round(pv*1.06,0),
                     check=f"plate bending: stiffness {MAT['PAHT']['E']*k**3/MAT['7075']['E']:.2f}x, strength {MAT['PAHT']['sf']*k*k/MAT['7075']['sy']:.2f}x of 7075 at yield (XY orientation)",
                     cad_change="envelope grows ~2.6x in thickness; re-check clearances")
        r["orig_mass_g"] = round(m0, 0); r["mat"] = "PAHT"
    elif cls == "SML_316L":
        m0 = v*MAT["316L"]["rho"]; k = 3.0; pv = v*k
        r.update(new="PAHT-CF, thickened x3 + embedded 4 mm steel dowels at pivots", reinforcement="steel dowels + inserts", printed_vol=round(pv,1), new_mass_g=round(pv*1.06 + 10,0),
                 check=f"stiffness {MAT['PAHT']['E']*k**3/MAT['316L']['E']:.2f}x of 316L plate -- LOW, needs FEA + load test", cad_change="redesign as ribbed printed part; 3x section", orig_mass_g=round(m0,0), mat="PAHT")
    else:
        m0 = v*MAT["PA12MJF"]["rho"]
        if teff <= 4.0:
            r.update(new="replaced by new Bob Bot shell set (PETG-CF)", reinforcement="M3 heat-set insert bosses", printed_vol=round(v,1), new_mass_g=round(v*MAT["PETGCF"]["rho"],0),
                     check="cosmetic / non-structural", cad_change="new shell CAD", mat="PETGCF")
        else:
            pv = v*0.6
            r.update(new="PAHT-CF (6 walls, 40 % gyroid)", reinforcement="M3 heat-set inserts", printed_vol=round(pv,1), new_mass_g=round(pv*1.06,0),
                     check=f"PAHT-CF tensile 88.7 MPa vs MJF PA12 ~48 MPa (HP); 60 % fill", cad_change="none (same geometry)", mat="PAHT")
        r["orig_mass_g"] = round(m0, 0)
    r["filament_cost"] = round(r["printed_vol"]*(1.06 if r["mat"]=="PAHT" else MAT["PETGCF"]["rho"])/1000*SCRAP*FIL[r["mat"]], 2)
    r["print_h"] = round(r["printed_vol"]/RATE[r["mat"]], 1)
    r["jlc3dp"] = "quote needed"
    rows.append(r)
json.dump(rows, open(f"{OUT}/parts.json", "w"), indent=0)
with open(f"{OUT}/parts.csv", "w", newline="") as f:
    keys = ["part","module","orig_process","orig_vol_cm3","orig_mass_g","new","reinforcement","printed_vol","new_mass_g","filament_cost","print_h","check","cad_change","jlc3dp","est_vol"]
    w = csv.DictWriter(f, fieldnames=keys, extrasaction="ignore"); w.writeheader(); [w.writerow(r) for r in rows]

# ---------------- stress checks ----------------
I_t = math.pi/64*(25**4-20**4); S_t = I_t/12.5
M = 45e3  # N mm, Menlo URDF cap at knee/hip pitch
sig = M/(2*S_t)
def contact(T, R, Npins, w_disk):
    F = T/(R/1000); n_eff = Npins/3.0; Fp = F/n_eff/2  # two disks share
    Es = 4120/(1-0.35**2)
    p = math.sqrt(Fp*Es/(math.pi*w_disk*2.0))
    return round(F,0), round(Fp,1), round(p,1)
cM = contact(20, 36, 16, 7); cL = contact(60, 48, 21, 11)
scr = lambda T, r, n: round(0.6*700*5.03/(T/(r/1000)/n), 1)
stress = [
 dict(item="Thigh/shin: 2x 6063-T5 tube 25x20 at 45 Nm (URDF cap)", value=f"sigma = {sig:.1f} MPa", allow="yield 145 MPa", sf=round(145/sig,1)),
 dict(item="Tube pair rotation over 150 mm at 45 Nm", value=f"{math.degrees(45e3*150/(68.9e3*2*I_t)):.2f} deg", allow="stiffness check", sf=None),
 dict(item="Ex-7075 plate printed x2.6 thicker (PAHT-CF, XY)", value="stiffness 1.01x, bending strength 1.89x", allow="7075-T6 plate", sf=1.0),
 dict(item="Ex-316L SLM part printed x3 thicker", value="stiffness 0.58x", allow="316L part", sf=0.58),
 dict(item="DIY-M cycloid pin contact at 20 Nm (Hertz, PA-CF)", value=f"{cM[2]} MPa", allow="88.7 MPa tensile (proxy)", sf=round(88.7/cM[2],2)),
 dict(item="DIY-L cycloid pin contact at 60 Nm (Hertz, PA-CF)", value=f"{cL[2]} MPa", allow="88.7 MPa tensile (proxy)", sf=round(88.7/cL[2],2)),
 dict(item="DIY-L output flange 6x M3 A2-70 in shear at 60 Nm (r 29 mm)", value=f"{60/(0.029*6):.0f} N per screw", allow="~2.1 kN", sf=scr(60, 29, 6)),
 dict(item="DIY-M output flange 6x M3 at 20 Nm (r 21.5 mm)", value=f"{20/(0.0215*6):.0f} N per screw", allow="~2.1 kN", sf=scr(20, 21.5, 6)),
]
json.dump(stress, open(f"{OUT}/stress.json", "w"), indent=1)

# ---------------- mass model ----------------
enc_total = sum(j["enc_mass"] for j in joints); diy_total = sum(j["diy_mass"] for j in joints)
rs_total = sum(RS[j["rs_alt"]]["mass"] for j in joints)
orig_parts = sum(r["orig_mass_g"] for r in rows)/1000; new_parts = sum(r["new_mass_g"] for r in rows)/1000
by_mod = {}
for r in rows:
    by_mod.setdefault(r["module"], 0.0); by_mod[r["module"]] += (r["new_mass_g"] - r["orig_mass_g"])/1000
mass = dict(menlo_total=G["total_mass"], enc_actuators=round(enc_total,2), diy_actuators=round(diy_total,2), rs_actuators=round(rs_total,2),
            orig_fab_parts=round(orig_parts,2), new_fab_parts=round(new_parts,2), struct_delta_by_module={k: round(v,3) for k, v in by_mod.items()},
            diy_total=round(G["total_mass"] - enc_total + diy_total - orig_parts + new_parts, 2),
            rs_total=round(G["total_mass"] - enc_total + rs_total, 2),
            note="battery mass assumed unchanged (Menlo 13S4P pack mass not published); fabricated-part masses from STEP volume x density")
json.dump(mass, open(f"{OUT}/mass.json", "w"), indent=1)

# ---------------- totals ----------------
nM = sum(1 for j in joints if j["diy"]=="DIY-M"); nL = len(joints)-nM
def packs(per_unit_rows_key, need, pack): return math.ceil(need/pack)
# 25-unit hardware bought in whole packs
need = {}
for s, n in (("M", nM), ("L", nL)):
    for b in A[s]["bom"]:
        if b["key"] == "filament": continue
        need[b["key"]] = need.get(b["key"], 0) + b["qty"]*n
act25 = []
for k, q in need.items():
    pk = {"b6803_10":10,"b6805_10":10,"b684_50":50,"dowel4x20_50":50,"insert_m3_100":100,"wire24":0.25}.get(k,1)
    if k == "wire24": npk = math.ceil(q/4)
    else: npk = math.ceil(q/pk)
    act25.append(dict(key=k, item=P[k]["item"], need=q, packs=npk, cost=round(npk*P[k]["price"],2), url=P[k]["url"], checked=P[k]["checked"]))
act_fil_kg = (A["M"]["printed_g"]*nM + A["L"]["printed_g"]*nL)/1000*SCRAP
act25.append(dict(key="paht_cf", item=f"PAHT-CF for actuators ({act_fil_kg:.2f} kg incl. 10 %)", need=act_fil_kg, packs=math.ceil(act_fil_kg), cost=round(math.ceil(act_fil_kg)*P["paht_cf"]["price"],2), url=P["paht_cf"]["url"], checked=P["paht_cf"]["checked"]))
act25_total = round(sum(x["cost"] for x in act25), 2)

paht_kg = sum(r["printed_vol"]*1.06 for r in rows if r["mat"]=="PAHT")/1000*SCRAP
petg_kg = sum(r["printed_vol"]*MAT["PETGCF"]["rho"] for r in rows if r["mat"]=="PETGCF")/1000*SCRAP
ntube_mm = sum(r.get("tube_mm",0) for r in rows)
struct = [
 dict(item=f"PAHT-CF structure ({paht_kg:.1f} kg)", cost=round(math.ceil(paht_kg)*P["paht_cf"]["price"],2), url=P["paht_cf"]["url"]),
 dict(item=f"PETG-CF shells ({petg_kg:.1f} kg)", cost=round(math.ceil(petg_kg)*P["petg_cf"]["price"],2), url=P["petg_cf"]["url"]),
 dict(item=f"6063 tube 25x20, {ntube_mm} mm total ({math.ceil(ntube_mm/600)} x 2-pack of 300 mm)", cost=round(math.ceil(ntube_mm/600)*P["tube25"]["price"],2), url=P["tube25"]["url"]),
 dict(item="M6 stainless rod 1 m (ankle push-rods)", cost=P["rod_m6"]["price"], url=P["rod_m6"]["url"]),
 dict(item="M3 heat-set inserts for structure + shells (4 x 100)", cost=round(4*P["insert_m3_100"]["price"],2), url=P["insert_m3_100"]["url"]),
 dict(item="Socket cap screw kits (2 x 880 pc) + shipping", cost=round(2*P["screws_kit"]["price"]+6.99,2), url=P["screws_kit"]["url"]),
]
battery = [
 dict(item="48x Samsung 35E (12S4P, 14 Ah, 43.2 V nominal)", cost=round(48*P["cell35e"]["price"],2), url=P["cell35e"]["url"]),
 dict(item="12S 30 A BMS", cost=P["bms12s"]["price"], url=P["bms12s"]["url"]),
 dict(item="50.4 V 3 A charger", cost=P["charger"]["price"], url=P["charger"]["url"]),
]
winder = [
 dict(item="2x LDO NEMA17 (spindle + traverse)", cost=round(2*P["nema17"]["price"],2), url=P["nema17"]["url"]),
 dict(item="Arduino Nano Every", cost=P["nano"]["price"], url=P["nano"]["url"]),
 dict(item="2x TMC2209", cost=round(2*P["tmc2209"]["price"],2), url=P["tmc2209"]["url"]),
 dict(item="2x GT2 20T pulley", cost=round(2*P["gt2"]["price"],2), url=P["gt2"]["url"]),
 dict(item="12 V 5 A PSU", cost=P["psu12"]["price"], url=P["psu12"]["url"]),
 dict(item="printed frame + wire guide (PETG-CF ~0.4 kg, from shell spool)", cost=0.0, url=""),
]
other_cart = 856.16   # every non-actuator line of the PR #41 cheapest cart (ENCOS subtotal 24,275.00 removed)
pcb = [dict(board="Motion control (106x98 mm, 4-layer)", fab="quote needed (exceeds 100x100 tier)"),
       dict(board="Power distribution (90x90 mm, 4-layer)", fab="from $7.50 / 5 pcs (secondary source); quote needed"),
       dict(board="Media hat (58x35.5 mm, 2-layer)", fab="from $2.00 / 5 pcs (jlcpcb.com)")]
pcb_floor = 9.50
sums = dict(actuators_25=act25_total, structure=round(sum(x["cost"] for x in struct),2), battery=round(sum(x["cost"] for x in battery),2),
            winder=round(sum(x["cost"] for x in winder),2), other_cart=other_cart, pcb_floor=pcb_floor)
sums["total"] = round(sum(sums.values()), 2)
rs_cost = sum(RS[j["rs_alt"]]["price"] for j in joints)
tot = dict(sums=sums, act25=act25, struct=struct, battery=battery, winder=winder, pcb=pcb, nM=nM, nL=nL,
           baseline=25131.16, baseline_actuators=24275.0,
           rs_mix=dict(actuators=rs_cost, total=round(rs_cost + other_cart + sums["structure"] + sums["battery"] + pcb_floor, 2),
                       note="RobStride single-unit prices; RS needs 48 V-class bus (works on 12S) and its own CAN protocol"),
           excluded=["shipping, duties and tax unless noted", "JLCPCB assembly + component cost (quote needed)", "Menlo items with no listed price in the PR #41 cart (McMaster lines, XT90 2+2)", "printer, soldering iron, tools"])
json.dump(tot, open(f"{OUT}/totals.json", "w"), indent=1)
print(json.dumps(A["M"], indent=0)[:600]); print(json.dumps({k:A["L"][k] for k in ("peak","cont","w_noload","w_at_peak","w_at_45","mass_g","unit_cost","print_h","armature")}))
print("M", {k:A["M"][k] for k in ("peak","cont","w_noload","w_at_peak","mass_g","unit_cost","print_h","armature")})
print(mass); print(sums, "rs", tot["rs_mix"]); print(stress)
