"""SmTIASv4 の LED モジュール（基板・カバー・台座・ねじ）を Fusion に作り直す.

Fusion の中で実行するスクリプト（MCP の fusion_mcp_execute で，このファイルを `exec` で読み込んで
`run` を呼ぶ．日本語の名前を化けさせないため中身を貼らずにファイルから読む．TECH_12）．

基板は `scripts/generate_led_module_boards.py`（Fusion Electronics の SmTIASv4_LED_side_v2 /
SmTIASv4_LED_bottom_v2）と同じ外形・部品の位置にする．LED は全部同じ高さ（Z −38．シミュの箱
では Z −35．TEST_21 結果 12）にそろえる．基板の座標 u（長さ方向）・v（幅方向．
KiCad の Y − 55．+12V の線が v < 0，GND の線が v > 0）を装置の座標へ写す:

- 左右用（LED 6 個）: y = u，右は x = 74 + v，左は x = −74 + v（左は右を平行移動したもの．同じ基板）
- 下用（LED 6 個．1 枚）: x = u・y = −84 − v（LED は下の壁から 6 mm．左右用と同じ）

カバーは SmTIASv3 の「LED 基板カバー」と同じ作り: 基板の部品の面（下）に重ねる厚さ 1 mm の白い板
（LED・定電流 IC・電源パッドの窓と M3 の穴）と，基板の内側の長い縁を隠す縁．カバーは 3D プリント
なので左右で鏡像にしてよい．ねじ（M3×8）はカバーの下から基板を通し，前側の台座の下穴に締める．台座は基板の上（顔の側）に
あり，横の壁・下の壁から張り出す棚にする．

実行すると次を作り直す（同じ名前のものは消してから作る）:
- コンポーネント「LEDモジュール」（基板・LED・定電流 IC・カバー）
- 筐体の前側の LED 台座（最後の 3 フィーチャ「基準フィーチャ*」「結合*」「結合*」を消してから足す）
- ねじ類の「M3x8 なべ小ねじ」の配置
"""

import adsk.core
import adsk.fusion

# 電源パッドはケーブル 1 本分（+12V と GND を幅の向きに並べた 2.0 × 3.0 mm）が長さの向きに 2 列
SIDE = {
    "u": (-18.3, 44.0), "chamfer": (38.0, 3.5), "holes": (-8.0, 40.0),
    "leds": (6.0, 10.0, 14.0, 26.0, 30.0, 34.0), "ccrs": (-2.0, 2.0, 18.0, 22.0),
    "pad_u": (-16.1, -12.6), "z_led": -38.0,
}
BOTTOM = {
    "u": (-41.3, 41.3), "chamfer": None, "holes": (-31.0, 31.0),
    "leds": (-25.0, -21.0, -17.0, 17.0, 21.0, 25.0), "ccrs": (-13.0, -9.0, 9.0, 13.0),
    "pad_u": (-39.1, -35.6, 35.6, 39.1), "z_led": -38.0,
}
BOTTOM_LED_Y = -84.0  # 下の LED 列の Y（下の壁の内面 −90 から 6 mm）
HALF_W = 5.0          # 基板の幅の半分（v = −5〜+5）
BOARD_T = 1.6
LED_H = 0.7           # LED の高さ（発光面 z_led から基板の下面まで）
COVER_T = 1.0         # カバーの板の厚さ（LED の発光面より 0.3 mm 下まで）
LIP_T = 1.0           # カバーの縁の厚さ
HOLE_D = 3.4          # カバー・基板のねじの通し穴
PILOT_D = 2.6         # 台座の下穴（M3 のタッピング）
PILOT_DEPTH = 6.0     # 下穴の深さ（M3×8 がカバーと基板の 2.6 mm を抜けて 5.4 mm かかる）
BOSS = 7.0            # 台座の一辺
tbm = adsk.fusion.TemporaryBRepManager.get()


def _box(lo, hi):
    c = adsk.core.Point3D.create(*((a + b) / 20 for a, b in zip(lo, hi, strict=True)))
    ob = adsk.core.OrientedBoundingBox3D.create(
        c, adsk.core.Vector3D.create(1, 0, 0), adsk.core.Vector3D.create(0, 1, 0),
        *((b - a) / 10 for a, b in zip(lo, hi, strict=True)))
    return tbm.createBox(ob)


def _cyl(x, y, z0, z1, d):
    return tbm.createCylinderOrCone(adsk.core.Point3D.create(x / 10, y / 10, z0 / 10), d / 20,
                                    adsk.core.Point3D.create(x / 10, y / 10, z1 / 10), d / 20)


def _sub(body, tool):
    tbm.booleanOperation(body, tool, adsk.fusion.BooleanTypes.DifferenceBooleanType)


def _union(body, tool):
    tbm.booleanOperation(body, tool, adsk.fusion.BooleanTypes.UnionBooleanType)


def _layouts():
    """(名前, 基板の定義, (u, v) → (x, y) の写し方, 内側の縁の v の向き) を返す."""
    return [
        ("右", SIDE, lambda u, v: (74.0 + v, u), -1),
        ("左", SIDE, lambda u, v: (-74.0 + v, u), +1),
        ("下", BOTTOM, lambda u, v: (u, BOTTOM_LED_Y - v), -1),
    ]


def _rect_uv(f, u0, u1, v0, v1):
    xs, ys = zip(*(f(u, v) for u in (u0, u1) for v in (v0, v1)), strict=True)
    return (min(xs), min(ys)), (max(xs), max(ys))


def _plate(spec, f, z0, z1):
    """基板の外形（左右用は上の端の両角を斜めに落とす）の板を z0〜z1 に作る."""
    u0, u1 = spec["u"]
    lo, hi = _rect_uv(f, u0, u1, -HALF_W, HALF_W)
    plate = _box((lo[0], lo[1], z0), (hi[0], hi[1], z1))
    if spec["chamfer"] is None:
        return plate
    uc, vc = spec["chamfer"]
    ox, oy = f(0.0, 0.0)

    def vec(du, dv):
        x, y = f(du, dv)
        return x - ox, y - oy

    for s in (1.0, -1.0):
        # 角を落とす線 (uc, s·5) → (u1, s·(5 − vc)) の外側を大きな箱で引く
        du, dv = u1 - uc, -s * vc
        n = (du * du + dv * dv) ** 0.5
        du, dv = du / n, dv / n
        nu, nv = vc / n * 1.0, s * (u1 - uc) / n  # 外向きの法線（長さ 1）
        mu, mv = (uc + u1) / 2 + nu * 10.0, s * (HALF_W + HALF_W - vc) / 2 + nv * 10.0
        cx, cy = f(mu, mv)
        lx, ly = vec(du, dv)
        wx, wy = vec(nu, nv)
        ob = adsk.core.OrientedBoundingBox3D.create(
            adsk.core.Point3D.create(cx / 10, cy / 10, (z0 + z1) / 20),
            adsk.core.Vector3D.create(lx, ly, 0), adsk.core.Vector3D.create(wx, wy, 0),
            4.0, 2.0, (z1 - z0 + 2.0) / 10)
        _sub(plate, tbm.createBox(ob))
    return plate


def _module(comp, base, name, spec, f, inward):
    z = spec["z_led"]
    zb0, zb1 = z + LED_H, z + LED_H + BOARD_T          # 基板の下面・上面
    zc0 = z - (COVER_T - LED_H)                         # カバーの下面
    board = _plate(spec, f, zb0, zb1)
    cover = _plate(spec, f, zc0, zb0)
    holes = []
    for hu in spec["holes"]:
        x, y = f(hu, 0.0)
        _sub(board, _cyl(x, y, zb0 - 1, zb1 + 1, 3.2))
        _sub(cover, _cyl(x, y, zc0 - 1, zb0 + 1, HOLE_D))
        holes.append((x, y))
    parts = []
    for lu in spec["leds"]:
        lo, hi = _rect_uv(f, lu - 1.4, lu + 1.4, -1.75, 1.75)
        parts.append(("LED", _box((lo[0], lo[1], z), (hi[0], hi[1], zb0))))
        lo, hi = _rect_uv(f, lu - 1.7, lu + 1.7, -2.05, 2.05)
        _sub(cover, _box((lo[0], lo[1], zc0 - 1), (hi[0], hi[1], zb0 + 0.1)))
    for cu in spec["ccrs"]:
        lo, hi = _rect_uv(f, cu - 0.8, cu + 0.8, -1.35, 1.35)
        parts.append(("定電流IC", _box((lo[0], lo[1], zb0 - 1.1), (hi[0], hi[1], zb0))))
        lo, hi = _rect_uv(f, cu - 1.1, cu + 1.1, -2.4, 2.4)
        _sub(cover, _box((lo[0], lo[1], zc0 - 1), (hi[0], hi[1], zb0 + 0.1)))
    for pu in spec["pad_u"]:
        lo, hi = _rect_uv(f, pu - 1.3, pu + 1.3, -4.0, 4.0)
        _sub(cover, _box((lo[0], lo[1], zc0 - 1), (hi[0], hi[1], zb0 + 0.1)))
    # 内側の長い縁を隠す縁（面取りの手前まで）
    u0, u1 = spec["u"]
    u_end = spec["chamfer"][0] if spec["chamfer"] else u1
    v_edge = inward * HALF_W
    lo, hi = _rect_uv(f, u0, u_end, v_edge, v_edge + inward * LIP_T)
    _union(cover, _box((lo[0], lo[1], zc0), (hi[0], hi[1], zb1 + 0.4)))
    comp.bRepBodies.add(board, base).name = f"基板_{name}"
    comp.bRepBodies.add(cover, base).name = f"カバー_{name}"
    for k, (kind, body) in enumerate(parts):
        comp.bRepBodies.add(body, base).name = f"{kind}_{name}_{k + 1}"
    return [(x, y, zc0, zb1) for x, y in holes]


def _delete_old_bosses(des, hcomp):
    tl = des.timeline
    items = []
    for i in range(tl.count):
        it = tl.item(i)
        try:
            pc = it.entity.parentComponent
        except Exception:  # タイムラインの一部の項目は親を持たない
            pc = None
        if pc == hcomp:
            items.append(it)
    last = items[-3:]
    names = [it.name for it in last]
    if not (names[0].startswith("基準フィーチャ") and all(n.startswith("結合") for n in names[1:])):
        raise RuntimeError(f"消そうとした筐体のフィーチャが LED 台座ではない: {names}")
    for it in reversed(last):
        it.entity.deleteMe()


def _bosses(hcomp, front, holes):
    hb = hcomp.features.baseFeatures.add()
    hb.startEdit()
    for i, (x, y, _zc0, zb1, kind) in enumerate(holes):
        if kind == "side":
            wall = (81.0 if y < 20 else 79.0) * (1 if x > 0 else -1)
            x0, x1 = sorted([x - BOSS / 2 * (1 if x > 0 else -1), wall])
            box = _box((x0, y - BOSS / 2, zb1), (x1, y + BOSS / 2, zb1 + 6.0))
        else:  # 下の壁（内面 Y −90）から張り出す棚
            box = _box((x - BOSS / 2, -91.0, zb1), (x + BOSS / 2, y + BOSS / 2, zb1 + 6.0))
        hcomp.bRepBodies.add(box, hb).name = f"LED台座_{i}"
        pilot = _cyl(x, y, zb1 - 0.1, zb1 + PILOT_DEPTH, PILOT_D)
        hcomp.bRepBodies.add(pilot, hb).name = f"LED下穴_{i}"
    hb.finishEdit()
    join = adsk.core.ObjectCollection.create()
    cut = adsk.core.ObjectCollection.create()
    for b in hcomp.bRepBodies:
        if b.name.startswith("LED台座"):
            join.add(b)
        if b.name.startswith("LED下穴"):
            cut.add(b)
    for tools, op in ((join, adsk.fusion.FeatureOperations.JoinFeatureOperation),
                      (cut, adsk.fusion.FeatureOperations.CutFeatureOperation)):
        ci = hcomp.features.combineFeatures.createInput(front, tools)
        ci.operation = op
        hcomp.features.combineFeatures.add(ci)


def _screws(root, holes):
    grp = [o.component for o in root.occurrences if o.component.name == "ねじ類"][0]
    for o in [o for o in grp.occurrences if o.component.name.startswith("M3x8")]:
        o.deleteMe()

    def mat(x, y, z):
        m = adsk.core.Matrix3D.create()
        m.translation = adsk.core.Vector3D.create(x / 10, y / 10, z / 10)
        return m

    x, y, zc0, _zb1, _k = holes[0]
    first = grp.occurrences.addNewComponent(mat(x, y, zc0))
    comp = first.component
    comp.name = "M3x8 なべ小ねじ"
    base = comp.features.baseFeatures.add()
    base.startEdit()
    head = _cyl(0, 0, -2.0, 0, 5.5)
    _union(head, _cyl(0, 0, 0, 8.0, 3.0))
    comp.bRepBodies.add(head, base).name = "M3x8"
    base.finishEdit()
    for x, y, zc0, _zb1, _k in holes[1:]:
        grp.occurrences.addExistingComponent(comp, mat(x, y, zc0))


def run(_context: str):
    app = adsk.core.Application.get()
    des = adsk.fusion.Design.cast(app.activeProduct)
    if app.activeDocument.name != "SmTIASv4":
        raise RuntimeError("SmTIASv4 をアクティブにしてから実行する")
    root = des.rootComponent
    hcomp = [o.component for o in root.occurrences if o.component.name == "筐体"][0]
    front = [b for b in hcomp.bRepBodies if b.name == "前側"][0]
    for o in list(root.occurrences):
        if o.component.name == "LEDモジュール":
            o.deleteMe()
    _delete_old_bosses(des, hcomp)
    occ = root.occurrences.addNewComponent(adsk.core.Matrix3D.create())
    comp = occ.component
    comp.name = "LEDモジュール"
    base = comp.features.baseFeatures.add()
    base.startEdit()
    holes = []
    for name, spec, f, inward in _layouts():
        kind = "side" if spec is SIDE else "bottom"
        holes += [(*h, kind) for h in _module(comp, base, name, spec, f, inward)]
    base.finishEdit()
    _bosses(hcomp, front, holes)
    _screws(root, holes)
    des.computeAll()
    bad = [b.name for b in comp.bRepBodies
           if any(front.pointContainment(v.geometry) == 0 for v in b.vertices)]
    tl = des.timeline
    unhealthy = [tl.item(i).name for i in range(tl.count)
                 if tl.item(i).healthState
                 != adsk.fusion.FeatureHealthStates.HealthyFeatureHealthState]
    print("bodies", comp.bRepBodies.count, "holes", len(holes))
    print("module parts inside front wall:", bad)
    print("unhealthy timeline items:", unhealthy)
