"""病院の車いす（自走用の標準形）を作る。森田茂さん（入院中の患者）が座る。
python3 wheelchair_build.py <out_dir>
前が -y、上が z、単位は m。根（Wheelchair）は床の中心で、座っている人の根（Morita_Shigeru）と同じ位置に置けば座った形が合う。
出力：wheelchair.blend・wheelchair.fbx・wheelchair_report.json
FBX は Unity 向け（前が Unity の +Z、上が +Y）。
回る部品は根を回る中心に置いてある：
- Wheel_L / Wheel_R：後ろの大きい車輪（車軸が中心。Unity の X 軸まわりに回す）
- Caster_L / Caster_R：前の小さい車輪の向き（支柱が中心。Unity の Y 軸まわりに回す）
- CasterWheel_L / CasterWheel_R：前の小さい車輪の回転（車軸が中心。Caster の子）
"""
import json
import math
import os
import sys

import bpy  # noqa: I001
from mathutils import Matrix, Vector

OUT = sys.argv[1]
os.makedirs(OUT, exist_ok=True)

# ---------- 寸法（m） ----------
SIDE_X = 0.225          # 横の枠の位置（座面の幅 0.42 + 枠）
SEAT_Z = 0.445          # 座面の布の上（この上にクッション 0.04）
CUSHION_TOP = 0.485     # 人が座る面
SEAT_Y0, SEAT_Y1 = -0.235, 0.205
BACK_TILT = math.radians(7)
WHEEL_R = 0.28          # 後ろの車輪（22 インチ）
AXLE = (0.150, WHEEL_R)  # (y, z)
WHEEL_X = 0.290
RIM_X = 0.318           # ハンドリム（手で回す輪）
CASTER_R = 0.075
CASTER_STEM = (-0.300, 0.255)  # 前の小さい車輪の支柱の上 (y, z)
CASTER_TRAIL = 0.035
FOOT_Z = 0.075          # 足のせ板の上
FOOT_Y0, FOOT_Y1 = -0.640, -0.420

SILVER = (196, 200, 206)
NAVY = (40, 58, 96)
CUSH = (78, 96, 128)
BLACK = (34, 34, 36)
TIRE = (52, 52, 54)


bpy.ops.wm.read_factory_settings(use_empty=True)


def mat(name, col, metal=0.0, rough=0.5):
    m = bpy.data.materials.new(name)
    m.use_nodes = True
    b = m.node_tree.nodes["Principled BSDF"]
    b.inputs["Base Color"].default_value = (*[(c / 255) ** 2.2 for c in col], 1)
    b.inputs["Metallic"].default_value = metal
    b.inputs["Roughness"].default_value = rough
    return m


M_SILVER = mat("WC_Frame_Mat", SILVER, 0.8, 0.35)
M_NAVY = mat("WC_Fabric_Mat", NAVY, 0.0, 0.85)
M_CUSH = mat("WC_Cushion_Mat", CUSH, 0.0, 0.9)
M_BLACK = mat("WC_Black_Mat", BLACK, 0.0, 0.6)
M_TIRE = mat("WC_Tire_Mat", TIRE, 0.0, 0.8)


def finish(ob, m, smooth=True):
    bpy.context.view_layer.objects.active = ob
    ob.select_set(True)
    if ob.type == "CURVE":
        bpy.ops.object.convert(target="MESH")
        ob = bpy.context.view_layer.objects.active
    ob.data.materials.clear()
    ob.data.materials.append(m)
    for p in ob.data.polygons:
        p.use_smooth = smooth
    ob.select_set(False)
    return ob


def tube(name, pts, r=0.011, m=M_SILVER, res=10):
    cu = bpy.data.curves.new(name, "CURVE")
    cu.dimensions = "3D"
    cu.bevel_depth = r
    cu.bevel_resolution = 2
    cu.use_fill_caps = True
    sp = cu.splines.new("POLY")
    sp.points.add(len(pts) - 1)
    for i, p in enumerate(pts):
        sp.points[i].co = (*p, 1)
    ob = bpy.data.objects.new(name, cu)
    bpy.context.scene.collection.objects.link(ob)
    return finish(ob, m)


def rounded_corner_path(pts, rad=0.04, n=5):
    """折れ線の角を丸める（パイプを曲げた形）"""
    P = [Vector(p) for p in pts]
    out = [P[0]]
    for i in range(1, len(P) - 1):
        a, b, c = P[i - 1], P[i], P[i + 1]
        u, v = (a - b).normalized(), (c - b).normalized()
        r = min(rad, (a - b).length * 0.45, (c - b).length * 0.45)
        p0, p1 = b + u * r, b + v * r
        for k in range(n + 1):
            t = k / n
            out.append((1 - t) ** 2 * p0 + 2 * (1 - t) * t * b + t * t * p1)
    out.append(P[-1])
    return [tuple(p) for p in out]


def box(name, c, size, m, bevel=0.006):
    bpy.ops.mesh.primitive_cube_add(size=1, location=c)
    ob = bpy.context.active_object
    ob.name = name
    ob.scale = size
    bpy.ops.object.transform_apply(scale=True)
    if bevel:
        md = ob.modifiers.new("b", "BEVEL")
        md.width = bevel
        md.segments = 3
        bpy.ops.object.modifier_apply(modifier="b")
    ob.select_set(False)
    return finish(ob, m)


def torus_x(name, center, R, r, m, seg=72, mseg=10):
    """x 軸に垂直な面の輪"""
    bpy.ops.mesh.primitive_torus_add(major_radius=R, minor_radius=r, major_segments=seg, minor_segments=mseg,
                                     location=center, rotation=(0, math.radians(90), 0))
    ob = bpy.context.active_object
    ob.name = name
    bpy.ops.object.transform_apply(rotation=True)
    ob.select_set(False)
    return finish(ob, m)


def cyl_x(name, center, r, depth, m, seg=32):
    bpy.ops.mesh.primitive_cylinder_add(radius=r, depth=depth, vertices=seg, location=center,
                                        rotation=(0, math.radians(90), 0))
    ob = bpy.context.active_object
    ob.name = name
    bpy.ops.object.transform_apply(rotation=True)
    ob.select_set(False)
    return finish(ob, m)


def join(name, obs, origin):
    bpy.ops.object.select_all(action="DESELECT")
    for o in obs:
        o.select_set(True)
    bpy.context.view_layer.objects.active = obs[0]
    if len(obs) > 1:
        bpy.ops.object.join()
    ob = bpy.context.view_layer.objects.active
    ob.name = name
    ob.data.name = name
    # 根を回る中心へ
    bpy.context.scene.cursor.location = origin
    bpy.ops.object.origin_set(type="ORIGIN_CURSOR")
    ob.select_set(False)
    return ob


# ---------- 枠 ----------
frame = []
seat_rail_z = SEAT_Z - 0.012
back_top = (SEAT_Y1 + math.sin(BACK_TILT) * 0.46, 0.905)
for s in (-1, 1):
    x = s * SIDE_X
    # 座面の横の棒 → 後ろの柱 → 押す手（ハンドル）
    frame.append(tube(f"side{s}", rounded_corner_path([
        (x, SEAT_Y0, 0.250), (x, SEAT_Y0, seat_rail_z), (x, SEAT_Y1, seat_rail_z),
        (x, back_top[0], back_top[1]), (x, back_top[0] + 0.095, back_top[1] + 0.005)], 0.035)))
    # 下の棒（前の支柱の上から後ろの車軸の下へ）
    frame.append(tube(f"low{s}", rounded_corner_path([
        (x, CASTER_STEM[0], CASTER_STEM[1]), (x, SEAT_Y0, 0.250), (x, AXLE[0] + 0.02, 0.225),
        (x, SEAT_Y1 + 0.03, seat_rail_z + 0.02)], 0.03)))
    # 前の支柱の筒
    frame.append(tube(f"stem{s}", [(x, CASTER_STEM[0], CASTER_STEM[1] - 0.015), (x, CASTER_STEM[0], CASTER_STEM[1] + 0.05)], 0.016))
    frame.append(tube(f"stemarm{s}", [(x, CASTER_STEM[0], CASTER_STEM[1] + 0.03), (x, SEAT_Y0, CASTER_STEM[1] + 0.03)], 0.010))
    # ひじかけの枠
    frame.append(tube(f"arm{s}", rounded_corner_path([
        (x, -0.150, seat_rail_z), (x, -0.150, 0.672), (x, 0.170, 0.672), (x, 0.170, seat_rail_z)], 0.03)))
    # 足のせのつり下げ
    frame.append(tube(f"hang{s}", rounded_corner_path([
        (x, SEAT_Y0, seat_rail_z), (x * 0.93, FOOT_Y1 + 0.02, FOOT_Z + 0.05), (x * 0.93, FOOT_Y1 + 0.02, FOOT_Z - 0.005),
        (s * 0.045, FOOT_Y1 + 0.02, FOOT_Z - 0.005)], 0.03), 0.0105))
    # 車軸の受け
    frame.append(tube(f"axleplate{s}", [(x, AXLE[0], AXLE[1]), (s * (WHEEL_X - 0.02), AXLE[0], AXLE[1])], 0.014))
    frame.append(tube(f"axlebrace{s}", [(x, AXLE[0], AXLE[1]), (x, AXLE[0] + 0.02, 0.225)], 0.012))
    # 後ろの転倒防止のバー（足で踏む棒）
    frame.append(tube(f"tip{s}", rounded_corner_path([
        (x, AXLE[0] + 0.02, 0.225), (x, AXLE[0] + 0.20, 0.13), (x, AXLE[0] + 0.25, 0.13)], 0.03), 0.0095))
# 座面の下のバツの棒（折りたたみ）
frame.append(tube("crossA", [(-SIDE_X, -0.03, seat_rail_z), (SIDE_X, 0.08, 0.235)], 0.010))
frame.append(tube("crossB", [(SIDE_X, -0.03, seat_rail_z), (-SIDE_X, 0.08, 0.235)], 0.010))
frame_ob = join("WC_Frame", frame, (0, 0, 0))

# ---------- 黒い部品（握り・ひじかけ・足のせ・転倒防止の先） ----------
blk = []
for s in (-1, 1):
    x = s * SIDE_X
    gy0, gz = back_top[0] + 0.035, back_top[1] + 0.003
    blk.append(tube(f"grip{s}", [(x, gy0, gz), (x, gy0 + 0.075, gz + 0.004)], 0.0155, M_BLACK))
    blk.append(box(f"armpad{s}", (x, 0.005, 0.690), (0.052, 0.30, 0.036), M_BLACK, 0.012))
    blk.append(box(f"foot{s}", (s * 0.105, (FOOT_Y0 + FOOT_Y1) / 2, FOOT_Z - 0.006), (0.150, FOOT_Y1 - FOOT_Y0, 0.012), M_BLACK, 0.004))
    blk.append(tube(f"tipcap{s}", [(x, AXLE[0] + 0.235, 0.13), (x, AXLE[0] + 0.265, 0.13)], 0.013, M_BLACK))
blk_ob = join("WC_Parts", blk, (0, 0, 0))

# ---------- 布（座面・背もたれ）とクッション ----------
seat = box("seat", (0, (SEAT_Y0 + SEAT_Y1) / 2, SEAT_Z - 0.006), (2 * SIDE_X - 0.004, SEAT_Y1 - SEAT_Y0, 0.012), M_NAVY, 0.004)
seat = join("WC_Seat", [seat], (0, 0, 0))
cush = box("cushion", (0, (SEAT_Y0 + SEAT_Y1) / 2 - 0.005, (SEAT_Z + CUSHION_TOP) / 2), (2 * SIDE_X - 0.03, SEAT_Y1 - SEAT_Y0 - 0.02, CUSHION_TOP - SEAT_Z), M_CUSH, 0.016)
cush = join("WC_Cushion", [cush], (0, 0, 0))
bh = 0.36
bc = (0, SEAT_Y1 + 0.012 + math.sin(BACK_TILT) * (0.10 + bh / 2), seat_rail_z + 0.10 + bh / 2)
back = box("back", bc, (2 * SIDE_X - 0.004, 0.012, bh), M_NAVY, 0.004)
back.rotation_euler = (-BACK_TILT, 0, 0)
bpy.context.view_layer.objects.active = back
back.select_set(True)
bpy.ops.object.transform_apply(rotation=True)
back.select_set(False)
back = join("WC_Back", [back], (0, 0, 0))

# ---------- 後ろの車輪（左右）。根は車軸 ----------
wheels = {}
for s, tag in ((1, "L"), (-1, "R")):   # L＝座った人の左＝+x
    c = (s * WHEEL_X, AXLE[0], AXLE[1])
    tire = torus_x("tire", c, WHEEL_R - 0.016, 0.016, M_TIRE, 96, 12)
    rim = torus_x("rim", c, WHEEL_R - 0.033, 0.006, M_SILVER, 96, 8)
    hub = cyl_x("hub", c, 0.032, 0.05, M_SILVER)
    parts = [tire, rim, hub]
    for k in range(18):   # スポーク（左右の面から交互に）
        a = 2 * math.pi * k / 18
        off = 0.018 if k % 2 else -0.018
        p0 = (c[0] + off, c[1] + 0.03 * math.cos(a + 0.2), c[2] + 0.03 * math.sin(a + 0.2))
        p1 = (c[0], c[1] + (WHEEL_R - 0.035) * math.cos(a), c[2] + (WHEEL_R - 0.035) * math.sin(a))
        parts.append(tube("spoke", [p0, p1], 0.0016, M_SILVER))
    hr = (s * RIM_X, AXLE[0], AXLE[1])
    parts.append(torus_x("handrim", hr, WHEEL_R - 0.030, 0.0085, M_SILVER, 96, 10))
    for k in range(6):
        a = 2 * math.pi * k / 6 + 0.3
        yy, zz = (WHEEL_R - 0.033) * math.cos(a), (WHEEL_R - 0.033) * math.sin(a)
        parts.append(tube("hrlink", [(s * (WHEEL_X + 0.006), c[1] + yy, c[2] + zz), (s * (RIM_X - 0.006), c[1] + yy, c[2] + zz)], 0.0045))
    wheels[tag] = join("Wheel_" + tag, parts, c)

# ---------- 前の小さい車輪（キャスター）。向きの根は支柱、回る根は車軸 ----------
casters = {}
for s, tag in ((1, "L"), (-1, "R")):
    x = s * SIDE_X
    stem_top = (x, CASTER_STEM[0], CASTER_STEM[1])
    axle = (x, CASTER_STEM[0] + CASTER_TRAIL, CASTER_R)
    fork = [tube("forkstem", [(x, stem_top[1], stem_top[2] - 0.02), (x, stem_top[1], CASTER_R + 0.10)], 0.010)]
    for d in (-1, 1):
        fork.append(tube("fork", rounded_corner_path([
            (x, stem_top[1], CASTER_R + 0.10), (x + d * 0.024, stem_top[1], CASTER_R + 0.10),
            (x + d * 0.024, axle[1], axle[2])], 0.012), 0.006))
    fork.append(box("forktop", (x, stem_top[1] + 0.008, CASTER_R + 0.103), (0.060, 0.030, 0.012), M_SILVER, 0.003))
    casters[tag] = join("Caster_" + tag, fork, stem_top)
    w = [cyl_x("cw", axle, CASTER_R, 0.030, M_TIRE, 40), cyl_x("cwhub", axle, 0.022, 0.034, M_SILVER, 24)]
    casters["W" + tag] = join("CasterWheel_" + tag, w, axle)

# ---------- 親子と根 ----------
root = bpy.data.objects.new("Wheelchair", None)
bpy.context.scene.collection.objects.link(root)
for ob in (frame_ob, blk_ob, seat, cush, back, wheels["L"], wheels["R"], casters["L"], casters["R"]):
    ob.parent = root
for tag in ("L", "R"):
    cw = casters["W" + tag]
    mw = cw.matrix_world.copy()
    cw.parent = casters[tag]
    cw.matrix_world = mw

bpy.ops.wm.save_as_mainfile(filepath=os.path.join(OUT, "wheelchair.blend"))
bpy.ops.export_scene.fbx(
    filepath=os.path.join(OUT, "wheelchair.fbx"), use_selection=False, object_types={"EMPTY", "MESH"},
    apply_unit_scale=True, apply_scale_options="FBX_SCALE_ALL", axis_forward="-Z", axis_up="Y",
    bake_space_transform=False, mesh_smooth_type="FACE", use_mesh_modifiers=False, use_triangles=True,
    add_leaf_bones=False, bake_anim=False, path_mode="STRIP", embed_textures=False,
)
tris = {o.name: sum(len(p.vertices) - 2 for p in o.data.polygons) for o in bpy.data.objects if o.type == "MESH"}
tris["_total_triangles"] = sum(tris.values())
mins = Vector((9, 9, 9))
maxs = Vector((-9, -9, -9))
for o in bpy.data.objects:
    if o.type == "MESH":
        for v in o.data.vertices:
            w = o.matrix_world @ v.co
            mins = Vector(map(min, mins, w))
            maxs = Vector(map(max, maxs, w))
rep = {"triangles": tris, "size_m": {"width_x": round(maxs.x - mins.x, 3), "length_y": round(maxs.y - mins.y, 3),
       "height_z": round(maxs.z - mins.z, 3)}, "bbox_min": [round(v, 3) for v in mins], "bbox_max": [round(v, 3) for v in maxs],
       "cushion_top_z": CUSHION_TOP, "wheel_radius": WHEEL_R, "axle_yz": AXLE, "caster_radius": CASTER_R,
       "push_handle_z": round(back_top[1] + 0.005, 3)}
json.dump(rep, open(os.path.join(OUT, "wheelchair_report.json"), "w"), ensure_ascii=False, indent=1)
print(json.dumps(rep, ensure_ascii=False))
