"""$1k humanoid design study: BOMs, mass, torque requirement scaling. Writes ../data/design.json + bom CSVs."""
import json, math, csv
from prices import P, J, FEES, FAB, C
D = "/workspace/asimov-guide/1k/data"
CD = "/workspace/asimov-guide/costdown/data"
AS_MASS, AS_H = 35.55, 1.2          # Asimov 1 sim model mass (kg), height (m)
CAP = {"hip_pitch": 45, "hip_roll": 45, "hip_yaw": 28, "knee": 45, "ankle_pitch": 40, "ankle_roll": 17, "waist_yaw": 40,
       "shoulder_pitch": 30, "shoulder_roll": 25, "shoulder_yaw": 20, "elbow": 12, "wrist_yaw": 12, "neck_yaw": 12, "neck_pitch": 12}
def req(m, h):  # Asimov URDF caps scaled by tau ~ m*g*L
    return {k: round(v * (m / AS_MASS) * (h / AS_H), 2) for k, v in CAP.items()}
# ---------------- custom FOC driver board (STM32G431 + JSM6288Q + 6x NCEP4090GU + MT6701 + TJA1051) ----------------
BOARD_MM = (45, 45); JOINTS = 315; BASIC = {"c1206", "c100n", "r10k", "r22"}
def pcba(nboards, vol=False):
    comp = sum(p["n"] * (p["vol"] if vol else p["q1"]) for p in J.values())
    area = BOARD_MM[0] * BOARD_MM[1] / 1e6
    ext = sum(1 for k in J if k not in BASIC)
    fixed = FEES["setup"] + FEES["stencil"] + FEES["handling"] + FEES["feeder_ext"] * ext + FEES["hand_solder"]
    if not vol:
        fab = area * FAB["rate_m2"] * nboards + (FAB["ex100_total"] - FAB["ex100_board"])  # overhead taken from JLC's 100-pc example
        asm = fixed + JOINTS * FEES["joint_q1"] * nboards
    else:
        fab = area * FAB["rate_m2"] * nboards + (FAB["ex500_total"] - FAB["ex500_board"]) / 500 * nboards
        asm = fixed * nboards / 2000 + JOINTS * FEES["joint_vol"] * nboards   # one setup per 2,000-board batch
    return dict(per_board=round(comp + (fab + asm) / nboards, 2), comp=round(comp, 2), fab=round(fab / nboards, 3), asm=round(asm / nboards, 3), ext_types=ext)
# ---------------- M50 actuator (5010 360KV + printed 25:1 cycloid) ----------------
KV, RATIO, ETA, I_PK, VBUS = 360, 25, 0.85, 30.0, 22.2
KT = 0.0298 * 310 / KV           # scaled from BHL's measured 5010 310KV (Kt 0.0298 Nm/A); assumption
R = 0.1462 * (310 / KV) ** 2     # phase R scaled with turns^2; assumption
W_NL = KV * VBUS * 2 * math.pi / 60 / RATIO
W_PK = W_NL * (1 - 1.5 * I_PK * R / VBUS)
TAU_PK = KT * I_PK * RATIO * ETA
P_CONT = 25.0                    # W copper loss allowed continuous; assumption (no thermal test)
TAU_CONT = math.sqrt(P_CONT / (1.5 * R)) * KT * RATIO * ETA
ARM = 3.301e-5 * RATIO ** 2      # BHL measured 5010 rotor inertia x N^2
M50 = dict(kt=round(KT, 4), r=round(R, 4), peak=round(TAU_PK, 1), cont=round(TAU_CONT, 1), w_nl=round(W_NL, 1), w_pk=round(W_PK, 1), armature=round(ARM, 4), mass=0.35,
           printed_kg=0.15, note="Kt, R scaled from BHL 5010 310KV measurements; continuous torque assumes 25 W copper loss; mass 0.35 kg is an estimate")
def m50_mech(vol):  # per-actuator mechanical parts (unit-share prices)
    return dict(motor=P["m5010"]["q1"], b6807=P["b6807"]["q1"], b6803=2 * P["b6803_10"]["q1"] / 10, b684=8 * P["b684_50"]["q1"] / 50,
                dowel=24 * P["dowel_50"]["q1"] / 50, magnet=P["magnet"]["q1"], pla=M50["printed_kg"] * 1.1 * P["pla"]["q1"])
# ---------------- servo specs ----------------
STS3250 = dict(peak=4.90, rated=1.57, w_nl=round(75 * 2 * math.pi / 60, 2), mass=0.0745, src="Feetech STS3250 datasheet: 50 kg.cm stall, 0.133 s/60 deg @12 V, 74.5 g")
STS3215 = dict(peak=2.94, w_nl=round(45 * 2 * math.pi / 60, 2), mass=0.055, src="Feetech ST-3215-C018 datasheet: ~30 kg.cm stall @12 V, 0.222 s/60 deg, 55 g")
# ---------------- mass models ----------------
CD_STRUCT = 10.2 + 3.3   # cost-down DIY printed structure + shells at 1.2 m (kg)
def struct_mass(h): return CD_STRUCT * (h / AS_H) ** 3
def line(cat, item, key, qty, unit, unit_vol=None, packs=None, note="", url=None, vol_label=""):
    u = unit if unit_vol is None else unit_vol
    q1 = (packs if packs is not None else qty) * unit
    return dict(cat=cat, item=item, key=key, qty=qty, unit=round(unit, 4), q1=round(q1, 2), vol=round(qty * u if packs is None else qty * u, 2), unit_vol=round(u, 4),
                vol_label=vol_label or ("published break" if unit_vol is not None and unit_vol != unit else "no published break: qty-1 price"), note=note,
                url=url or (P[key]["url"] if key in P else ""), seller=P[key]["seller"] if key in P else "")
def nano():
    h, nleg, narm = 0.6, 12, 7
    L = []
    L.append(line("actuators", P["sts3250"]["item"], "sts3250", nleg, P["sts3250"]["q1"], note="hips, knees, ankles"))
    L.append(line("actuators", P["sts3215"]["item"], "sts3215", narm, P["sts3215"]["q1"], P["sts3215"]["vol"], note="shoulder pitch/roll, elbow x2, neck yaw", vol_label="WowRobo 10-pack price"))
    L.append(line("compute", P["pi_zero2w"]["item"], "pi_zero2w", 1, P["pi_zero2w"]["q1"]))
    L.append(line("compute", P["bus_adapter"]["item"], "bus_adapter", 1, P["bus_adapter"]["q1"]))
    L.append(line("sensing", P["bno085"]["item"], "bno085", 1, P["bno085"]["q1"]))
    L.append(line("sensing", P["cam3"]["item"], "cam3", 1, P["cam3"]["q1"]))
    L.append(line("sensing", P["zero_cam_cable"]["item"], "zero_cam_cable", 1, P["zero_cam_cable"]["q1"]))
    L.append(line("power", P["buck5v"]["item"], "buck5v", 1, P["buck5v"]["q1"]))
    L.append(line("battery", P["p42a"]["item"] + " (3S2P, 12.6 V max)", "p42a", 6, P["p42a"]["q1"]))
    L.append(line("battery", P["bms3s"]["item"], "bms3s", 1, P["bms3s"]["q1"]))
    L.append(line("battery", P["chg3s"]["item"], "chg3s", 1, P["chg3s"]["q1"]))
    L.append(line("battery", P["nickel"]["item"], "nickel", 0.1, P["nickel"]["q1"], packs=1, note="~1 m used"))
    sm = struct_mass(h); kg = sm * 1.1
    L.append(line("structure", f"PLA, {kg:.2f} kg incl. 10 % waste (structure + shells)", "pla", kg, P["pla"]["q1"], packs=math.ceil(kg)))
    L.append(line("structure", P["screws"]["item"], "screws", 0.25, P["screws"]["q1"], packs=1, note="kit shared ~4 robots at volume"))
    L.append(line("structure", P["inserts"]["item"], "inserts", 1, P["inserts"]["q1"]))
    L.append(line("wiring", P["wire16"]["item"], "wire16", 0.05, P["wire16"]["q1"], packs=1, note="~1.5 m used; servos ship with bus leads"))
    mass = dict(servos=nleg * STS3250["mass"] + narm * STS3215["mass"], battery=6 * 0.070 + 0.03, electronics=0.10, wiring=0.10, structure=sm)
    return dict(name="Bob Nano", height=h, dof=nleg + narm, lines=L, mass=mass, actuators="Feetech bus servos")
def mini():
    h, n = 0.8, 20; nb = n + 2
    L = []
    mq = m50_mech(False)
    L.append(line("actuators", P["m5010"]["item"], "m5010", n, P["m5010"]["q1"]))
    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)))
    L.append(line("actuators", P["magnet"]["item"], "magnet", n, 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} (20 joints + 2 USB-CAN bridges), JLCPCB 4-layer {BOARD_MM[0]}x{BOARD_MM[1]} mm", 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, 22,000 boards", note="unbuilt design; parts from JLCPCB API", url=FEES["src"], seller="JLCPCB"))
    L.append(line("compute", P["pi5_2g"]["item"], "pi5_2g", 1, P["pi5_2g"]["q1"]))
    L.append(line("sensing", P["bno085"]["item"], "bno085", 1, P["bno085"]["q1"], 1.5055 + 0.0, vol_label="volume swaps in ICM-42688-PC on the bridge board (LCSC C48586483, $1.5055 @1000)"))
    L.append(line("sensing", P["cam3"]["item"], "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("power", P["buck5v"]["item"], "buck5v", 1, P["buck5v"]["q1"]))
    L.append(line("battery", P["p42a"]["item"] + " (6S2P, 25.2 V max)", "p42a", 12, 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.2, P["nickel"]["q1"], packs=1, note="~2 m used"))
    sm = struct_mass(h); pla = (sm * 0.6 + n * M50["printed_kg"]) * 1.1; cf = sm * 0.4 * 1.1
    L.append(line("structure", f"PLA, {pla:.2f} kg incl. 10 % waste (shells, non-load parts, actuator housings + cycloid discs)", "pla", pla, P["pla"]["q1"], packs=math.ceil(pla)))
    L.append(line("structure", f"PETG-CF, {cf:.2f} kg incl. 10 % waste (load-path links)", "petgcf", cf, P["petgcf"]["q1"], packs=math.ceil(cf)))
    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.13, P["wire16"]["q1"], packs=1, note="~4 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"]))
    mass = dict(actuators=n * M50["mass"], battery=12 * 0.070 + 0.06, electronics=0.12, wiring=0.25, structure=sm)
    return dict(name="Bob Mini", height=h, dof=n, lines=L, mass=mass, actuators="M50: 5010 360KV + printed 25:1 cycloid + custom FOC board", m50=M50,
                m50_unit_q1=round(sum(mq.values()) + p1["per_board"], 2), m50_unit_vol=round(sum(m50_mech(True).values()) + pv["per_board"], 2), m50_mech=mq, pcba_q1=p1, pcba_vol=pv)
def lite():
    AJ = json.load(open(f"{CD}/actuators.json")); T = json.load(open(f"{CD}/totals.json"))["sums"]; A = AJ["actuators"]
    drop = ["left_shoulder_yaw_joint", "right_shoulder_yaw_joint", "left_wrist_yaw_joint", "right_wrist_yaw_joint", "neck_pitch_joint"]
    keep = [j for j in AJ["joints"] if j["role"] not in drop]
    nL = sum(j["diy"] == "DIY-L" for j in keep); nM = sum(j["diy"] == "DIY-M" for j in keep)
    p1, pv = pcba(22), pcba(22000, vol=True)
    mechL = A["L"]["unit_cost"] - 69 - 19; mechM = A["M"]["unit_cost"] - 69
    L = [dict(cat="actuators", item=f"Cost-down DIY-L mechanics (rewound M6C12, PAHT-CF cycloid), moteus-c1 + heat spreader removed", key="diyL", qty=nL, unit=mechL, q1=round(nL * mechL, 2), unit_vol=mechL, vol=round(nL * mechL, 2), vol_label="no published break: qty-1 price", note="from /bob-bot/cost-down/", url="https://wyat.dev/bob-bot/cost-down/", seller=""),
         dict(cat="actuators", item=f"Cost-down DIY-M mechanics, moteus-c1 removed", key="diyM", qty=nM, unit=mechM, q1=round(nM * mechM, 2), unit_vol=mechM, vol=round(nM * mechM, 2), vol_label="no published break: qty-1 price", note="from /bob-bot/cost-down/", url="https://wyat.dev/bob-bot/cost-down/", seller=""),
         dict(cat="actuators", item="Custom FOC driver PCBA x22 (needs a 60-80 V FET / buck variant for 12S; priced as the 24 V board = lower bound)", key="pcba", qty=22, unit=p1["per_board"], q1=round(22 * p1["per_board"], 2), unit_vol=pv["per_board"], vol=round(22 * pv["per_board"], 2), vol_label="LCSC 1000+ tiers + JLC fees", note="lower bound", url=FEES["src"], seller="JLCPCB"),
         dict(cat="structure", item="Cost-down structure (PAHT-CF + PETG-CF shells, tube, rods, inserts, screws)", key="cd_struct", qty=1, unit=T["structure"], q1=T["structure"], unit_vol=T["structure"], vol=T["structure"], vol_label="no published break: qty-1 price", note="", url="https://wyat.dev/bob-bot/cost-down/", seller=""),
         dict(cat="battery", item="Cost-down 12S4P pack + BMS + charger", key="cd_batt", qty=1, unit=T["battery"], q1=T["battery"], unit_vol=T["battery"], vol=T["battery"], vol_label="no published break: qty-1 price", note="", url="https://wyat.dev/bob-bot/cost-down/", seller=""),
         dict(cat="compute", item="Cost-down non-actuator cart (compute, sensors, wiring, PCBs)", key="cd_other", qty=1, unit=T["other_cart"], q1=T["other_cart"], unit_vol=T["other_cart"], vol=T["other_cart"], vol_label="no published break: qty-1 price", note="", url="https://wyat.dev/bob-bot/cost-down/", seller="")]
    m_rm = sum(j["diy_mass"] for j in AJ["joints"] if j["role"] in drop)
    return dict(name="Bob 1.2 Lite", height=1.2, dof=20, lines=L, mass=dict(total_from_costdown=38.601 - m_rm), nL=nL, nM=nM, mechL=mechL, mechM=mechM,
                actuators="cost-down DIY actuators, custom driver", drop=drop)
def totals(d):
    q1 = round(sum(l["q1"] for l in d["lines"]), 2); 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["total_q1"], d["total_vol"] = q1, vol; d["by_cat"] = {k: [round(a, 2), round(b, 2)] for k, b2 in [(0, 0)] for k, (a, b) in cats.items()}
    d["mass_total"] = round(sum(d["mass"].values()), 2); d["req"] = req(d["mass_total"], d["height"])
    return d
if __name__ == "__main__":
    out = dict(checked=C, designs=[totals(nano()), totals(mini()), totals(lite())], sts3250=STS3250, sts3215=STS3215, m50=M50)
    for d in out["designs"]:
        print(f"{d['name']:14s} h {d['height']} m  {d['dof']} DOF  mass {d['mass_total']} kg  qty1 ${d['total_q1']:,.2f}  vol ${d['total_vol']:,.2f}  ", d["by_cat"])
        with open(f"{D}/bom_{d['name'].lower().replace(' ', '_').replace('.', '')}.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"]])
    mi = out["designs"][1]
    print("M50", M50, "unit q1", mi["m50_unit_q1"], "vol", mi["m50_unit_vol"]); print("PCBA", mi["pcba_q1"], mi["pcba_vol"])
    print("req nano", out["designs"][0]["req"]); print("req mini", mi["req"]); print("lite", out["designs"][2]["mass"], out["designs"][2]["nL"], out["designs"][2]["nM"])
    json.dump(out, open(f"{D}/design.json", "w"), indent=1)
