"""Bob Helper useful-task study: requirements, BOMs (qty 1 and qty 1,000), legged comparison. Writes ../data/*.json, bom CSVs.
Prices fetched 2026-11-17. Volume column uses published multi-qty breaks where they exist, else the qty-1 price (labelled)."""
import json, math, csv, sys
from prices import P, J, FEES, FAB, C
from prices_useful import P2, C2, MARKET, SOFT
import design as DZ
sys.path.insert(0, "../sim"); import model as SM
D = "/workspace/asimov-guide/useful/data"
P.update(P2)
line = DZ.line; M50 = DZ.M50; pcba = DZ.pcba
SIM = {n: json.load(open(f"{D}/sim_{n}.json")) for n in ("helper", "helper_s")}
def m50_lines(n, L, note):
    L.append(line("actuators", P["m5010"]["item"], "m5010", n, P["m5010"]["q1"], note=note))
    L.append(line("actuators", P["b6807"]["item"], "b6807", n, P["b6807"]["q1"]))
    L.append(line("actuators", P["b6803_10"]["item"], "b6803_10", 2 * n / 10, P["b6803_10"]["q1"], packs=math.ceil(2 * n / 10)))
    L.append(line("actuators", P["b684_50"]["item"], "b684_50", 8 * n / 50, P["b684_50"]["q1"], packs=math.ceil(8 * n / 50)))
    L.append(line("actuators", P["dowel_50"]["item"] + " (cycloid ring + output pins)", "dowel_50", 24 * n / 50, P["dowel_50"]["q1"], packs=math.ceil(24 * n / 50)))
def common(L, nb, nm50_total, pla_kg, petg_kg, n3215, n3250):
    if n3250: L.append(line("actuators", P["sts3250"]["item"], "sts3250", n3250, P["sts3250"]["q1"]))
    L.append(line("actuators", P["sts3215"]["item"], "sts3215", n3215, P["sts3215"]["q1"], P["sts3215"]["vol"], vol_label="WowRobo 10-pack price"))
    L.append(line("actuators", P["bus_adapter"]["item"], "bus_adapter", 1, P["bus_adapter"]["q1"]))
    L.append(line("actuators", P["magnet"]["item"] + " (one per FOC board encoder)", "magnet", nb - 1, P["magnet"]["q1"]))
    p1, pv = pcba(nb), pcba(nb * 1000, vol=True)
    L.append(dict(cat="actuators", item=f"Custom FOC driver PCBA x{nb} ({nb - 1} motor boards + 1 USB-CAN bridge), JLCPCB 4-layer 45x45 mm (same board as /bob-bot/1k/)", key="pcba", qty=nb,
                  unit=p1["per_board"], q1=round(p1["per_board"] * nb, 2), unit_vol=pv["per_board"], vol=round(pv["per_board"] * nb, 2),
                  vol_label="LCSC 1000+ tiers + JLC fees", note="unbuilt design; parts priced from the JLCPCB parts API", url=FEES["src"], seller="JLCPCB"))
    # lift
    L.append(line("lift", P["tr8x2"]["item"], "tr8x2", 1, P["tr8x2"]["q1"], note="driven directly by a bare 5010 + FOC board; 2 mm lead self-locks (no brake needed)"))
    L.append(line("lift", P["mgn12"]["item"], "mgn12", 2, P["mgn12"]["q1"]))
    L.append(line("lift", P["m5010"]["item"] + " (lift motor, no gearbox)", "m5010", 1, P["m5010"]["q1"]))
    # base
    L.append(line("base", P["caster4"]["item"], "caster4", 1, P["caster4"]["q1"]))
    L.append(line("structure", P["vslot1m"]["item"] + " (base frame 4 x 0.5 m + column 2 x 1.0 m)", "vslot1m", 4, P["vslot1m"]["q1"]))
    # compute / sensing
    L.append(line("compute", P["pi5_2g"]["item"] + " (cameras, control loop, Wi-Fi to the policy GPU)", "pi5_2g", 1, P["pi5_2g"]["q1"]))
    L.append(line("sensing", P["cam3"]["item"] + " (head camera, CSI)", "cam3", 1, P["cam3"]["q1"]))
    L.append(line("sensing", P["zero_cam_cable"]["item"] + " (22-pin, fits Pi 5)", "zero_cam_cable", 1, P["zero_cam_cable"]["q1"]))
    L.append(line("sensing", P["usbcam"]["item"] + " (one per wrist)", "usbcam", 2, P["usbcam"]["q1"]))
    L.append(line("power", P["buck5v"]["item"], "buck5v", 1, P["buck5v"]["q1"]))
    # battery 6S4P
    L.append(line("battery", P["p42a"]["item"] + " (6S4P, 21.6 V nominal, ~363 Wh)", "p42a", 24, P["p42a"]["q1"]))
    L.append(line("battery", P["bms6s"]["item"], "bms6s", 1, P["bms6s"]["q1"]))
    L.append(line("battery", P["chg6s"]["item"], "chg6s", 1, P["chg6s"]["q1"]))
    L.append(line("battery", P["nickel"]["item"], "nickel", 0.3, P["nickel"]["q1"], packs=1, note="~3 m used"))
    # printed + hardware
    L.append(line("structure", f"PLA, {pla_kg:.1f} kg incl. 10 % waste (actuator housings, cycloid discs, torso, head, shells)", "pla", pla_kg, P["pla"]["q1"], packs=math.ceil(pla_kg)))
    L.append(line("structure", f"PETG-CF, {petg_kg:.1f} kg incl. 10 % waste (arm links, lift carriage, wheel hubs)", "petgcf", petg_kg, P["petgcf"]["q1"], packs=math.ceil(petg_kg)))
    L.append(line("structure", P["tpu"]["item"], "tpu", 0.5, P["tpu"]["q1"], packs=1, note="~0.5 kg used"))
    L.append(line("structure", P["screws"]["item"], "screws", 0.5, P["screws"]["q1"], packs=1, note="kit shared 2 robots at volume"))
    L.append(line("structure", P["inserts"]["item"], "inserts", 2, P["inserts"]["q1"]))
    L.append(line("wiring", P["wire16"]["item"], "wire16", 0.15, P["wire16"]["q1"], packs=1, note="~5 m pair used"))
    L.append(line("wiring", P["gh_pigtail"]["item"] + " (CAN daisy chain, 2 per board)", "gh_pigtail", 2 * nb, P["gh_pigtail"]["q1"]))
    return p1, pv
def helper():
    L = []; n = 10
    m50_lines(n, L, "8 arm joints (shoulder pitch/roll/yaw + elbow, x2) + 2 drive wheels")
    pla = (n * M50["printed_kg"] + 0.6 + 0.9 + 0.4 + 0.2) * 1.1; petg = 1.2 * 1.1
    p1, pv = common(L, nb=n + 2, nm50_total=n, pla_kg=pla, petg_kg=petg, n3215=6, n3250=2)
    return dict(key="helper", name="Bob Helper", lines=L, joints="2 x (4 M50 + STS3250 wrist pitch + STS3215 wrist roll + STS3215 gripper), 2-DOF head, lift, 2 wheels",
                dof=2 * 7 + 2 + 1 + 2, mass=SIM["helper"]["tip"][0]["mass_kg"], pcba_q1=p1, pcba_vol=pv)
def helper_s():
    L = []; n = 2
    m50_lines(n, L, "2 drive wheels only")
    pla = (n * M50["printed_kg"] + 0.4 + 0.9 + 0.4 + 0.2) * 1.1; petg = 0.8 * 1.1
    p1, pv = common(L, nb=n + 2, nm50_total=n, pla_kg=pla, petg_kg=petg, n3215=10, n3250=6)
    return dict(key="helper_s", name="Bob Helper S", lines=L, joints="2 x (3 STS3250 + 4 STS3215 incl. gripper), 2-DOF head, lift, 2 wheels",
                dof=2 * 7 + 2 + 1 + 2, mass=SIM["helper_s"]["tip"][0]["mass_kg"], pcba_q1=p1, pcba_vol=pv)
def teleop():
    L = [line("teleop", P["sts3215"]["item"] + " (2 leader arms x 7: 6 joints + trigger)", "sts3215", 14, P["sts3215"]["q1"], P["sts3215"]["vol"], vol_label="WowRobo 10-pack price"),
         line("teleop", P["bus_adapter"]["item"], "bus_adapter", 2, P["bus_adapter"]["q1"]),
         line("teleop", "PLA 1 kg (leader arm links)", "pla", 1, P["pla"]["q1"])]
    return dict(key="teleop", name="Leader-arm teleop kit", lines=L)
def totals(d):
    d["total_q1"] = round(sum(l["q1"] for l in d["lines"]), 2); d["total_vol"] = round(sum(l["vol"] for l in d["lines"]), 2)
    cats = {}
    for l in d["lines"]:
        c = cats.setdefault(l["cat"], [0, 0]); c[0] += l["q1"]; c[1] += l["vol"]
    d["by_cat"] = {k: [round(a, 2), round(b, 2)] for k, (a, b) in cats.items()}; return d
REQ = [  # task -> requirement (sources: furniture standards / product specs where cited; else stated as an assumption)
 dict(task="Pick and carry household objects (mug, plate stack, bottle, folded laundry)", need="1 kg in one gripper close to the body, 0.3-0.5 kg at arm's length; 1.5 kg two-handed", basis="assumption: covers mugs (~0.35 kg), 1 L bottle (~1.05 kg), a dinner plate (~0.5 kg)"),
 dict(task="Counter and table work", need="reach 40 cm past the edge at 0.75 m (table) and 0.91 m (counter)", basis="0.91 m (36 in) is the common US counter height; table ~0.75 m (assumption)"),
 dict(task="Shelves / cabinets", need="first upper-cabinet shelf ~1.45 m, 10 cm in", basis="assumption: 54 in (1.37 m) cabinet bottom + 8 cm"),
 dict(task="Floor / dishwasher / laundry basket", need="reach the floor 10 cm past the bumper; dishwasher lower rack ~0.30 m, 35 cm deep", basis="assumption"),
 dict(task="Doors and drawers", need="handle at ~1.0 m; pull 20-40 N", basis="assumption (drawer slides / latches)"),
 dict(task="Wipe surfaces", need="3-10 N normal force while sweeping, compliant", basis="backdrivable low-ratio actuators give force control for free"),
 dict(task="Grip", need="hold 1 kg against gravity with mu 0.5 and safety factor 2: F >= m g SF / (2 mu) = 19.6 N per finger", basis="Coulomb friction"),
 dict(task="Arm DOF", need=">= 6 per arm + 1-DOF gripper (plus lift + base give redundancy)", basis="6 DOF = arbitrary hand pose"),
 dict(task="Cameras", need="head camera + one per wrist", basis="ACT / Mobile ALOHA / SmolVLA setups use a top view + wrist views"),
 dict(task="Compute", need="policy inference: offboard consumer GPU over Wi-Fi (LeRobot async inference) or onboard Jetson", basis="SmolVLA runs on consumer GPU; async inference in LeRobot"),
 dict(task="Runtime", need=">= 2 h of mixed work", basis="assumption; 1X NEO reports ~4 h, Unitree G1 ~2 h"),
]
POWER = dict(pi5=8, cams=4, servos_idle=4, arms_hold=2 * 2 * 1.5 * (6.5 / 6.8) ** 2 * 25 / 4, drive_avg=15, lift_avg=3)   # W, estimates
def runtime(jetson=False):
    p = sum(POWER.values()) + (15 if jetson else 0); wh = 24 * 3.6 * 4.2 * 0.8   # 24 cells x 3.6 V x 4.2 Ah, 80 % usable
    return round(p, 1), round(wh, 0), round(wh / p, 1)
if __name__ == "__main__":
    ds = [totals(helper()), totals(helper_s())]; tk = totals(teleop())
    jet = P["jetson"]["q1"] - P["pi5_2g"]["q1"]
    for d in ds:
        d["with_jetson_q1"] = round(d["total_q1"] + jet, 2); d["with_jetson_vol"] = round(d["total_vol"] + jet, 2)
        d["with_teleop_q1"] = round(d["total_q1"] + tk["total_q1"], 2)
        print(f"{d['name']:14s} mass {d['mass']} kg  qty1 ${d['total_q1']:,.2f}  vol ${d['total_vol']:,.2f}  +jetson ${d['with_jetson_q1']:,.2f}", d["by_cat"])
        with open(f"{D}/bom_{d['key']}.csv", "w", newline="") as f:
            w = csv.writer(f); w.writerow(["category", "item", "qty", "unit_usd", "qty1_line_usd", "unit_usd_at_1000", "line_usd_at_1000", "volume_basis", "seller", "url", "checked", "note"])
            for l in d["lines"]: w.writerow([l["cat"], l["item"], l["qty"], l["unit"], l["q1"], l["unit_vol"], l["vol"], l["vol_label"], l["seller"], l["url"], C, l["note"]])
    print("teleop", tk["total_q1"], tk["total_vol"])
    with open(f"{D}/bom_teleop.csv", "w", newline="") as f:
        w = csv.writer(f); w.writerow(["category", "item", "qty", "unit_usd", "qty1_line_usd", "unit_usd_at_1000", "line_usd_at_1000", "volume_basis", "seller", "url", "checked", "note"])
        for l in tk["lines"]: w.writerow([l["cat"], l["item"], l["qty"], l["unit"], l["q1"], l["unit_vol"], l["vol"], l["vol_label"], l["seller"], l["url"], C, l["note"]])
    # legged comparison (rough estimate, not a BOM)
    h = ds[0]; m50q1 = 58.97; m50v = 47.32
    legged = dict(note="rough estimate, not a BOM: Helper upper body on 12 leg joints. Knee torque for a ~25 kg, 1.1 m robot scales from Asimov's 45 Nm cap to ~29 Nm (tau ~ m g L), "
                       "beyond one M50 (16.4 Nm peak), so each leg joint is costed as two M50s ganged (estimate). Base, wheels, casters and lift removed; IMU added.",
                  knee_req_Nm=round(45 * (25 / 35.55) * (1.1 / 1.2), 1),
                  q1=round(h["total_q1"] - sum(l["q1"] for l in h["lines"] if l["cat"] in ("base", "lift")) - 2 * m50q1 + 24 * m50q1 + 12 * 2 * 22.51 + 29.50, 0),
                  vol=round(h["total_vol"] - sum(l["vol"] for l in h["lines"] if l["cat"] in ("base", "lift")) - 2 * m50v + 24 * m50v + 12 * 2 * 10.86 + 29.50, 0))
    print("legged", legged)
    rt = dict(pi=runtime(False), jetson=runtime(True), power=POWER)
    print("runtime", rt)
    json.dump(dict(checked=C, designs=ds, teleop=tk, jetson_delta=jet, legged=legged, req=REQ, market=MARKET, soft=SOFT, runtime=rt, m50=M50,
                   sim={k: v for k, v in SIM.items()}), open(f"{D}/design_useful.json", "w"), indent=1)
