"""SmTIASv4 の前側の鼻の穴を閉じ，上の縁の丸みの上に鼻当てを付ける.

Fusion の中で実行するスクリプト（MCP の fusion_mcp_execute で `exec(open(パス).read())` の形で
読み込んで `run` を呼ぶ．TECH_12）．

TIAS（研究室の旧機）のスペーサの鼻当て（口の穴の上の縁に付いた，幅 28 mm・太さ 6 mm で先の
丸い棒）にならう（2026-11-09 ユーザー）．前側は顔の面をベッドに付けて刷るので，TIAS のように
顔の面より外へは出さず，上の縁の丸みの上に乗せて顔の側の面を顔の面（Z 0）にそろえる．

- 鼻の穴の切り欠き（「鼻の穴 (1)」）は抑制する（消さないので抑制を外せば戻る）
- 口の穴は元の形のまま．ただし口の穴（顔の面から 4 mm）の奥に残る上の壁の棚を，口の穴の形の中で
  鼻当ての内側の面より手前だけ SHELF_Z まで削る（鼻当ての下を開ける．2026-11-09 ユーザー）．
  鼻当ての真下の壁は残す
- 鼻当て: X 方向の棒（半径 NOSE_R の円柱 + 両端の半球．全長 NOSE_LEN）．中心は Y NOSE_Y・
  Z NOSE_Z で，Z 0 より外は切り落とす（顔の側が幅約 3 mm の平らな面になり，ベッドに付く）

実行すると前回の鼻当てを消して作り直す．
"""

import adsk.core
import adsk.fusion

NOSE_LEN = 28.0  # 全長（TIAS と同じ）
NOSE_R = 3.0  # 太さ 6 mm の半径（TIAS と同じ）
NOSE_Y = 58.0  # 棒の中心（上の壁の内側にそろう 57 から 1 mm 上げた．2026-11-09 ユーザー）
NOSE_Z = -2.6  # 棒の中心の深さ（Z 0 で切って顔の側を平らにする）
SHELF_Z = -6.5  # 棚を削る深さ（上の壁の内側の面がここで Y > 鼻当ての内側になる）
NOSE_NAME = "鼻当て"
NOSE_HOLE = "鼻の穴 (1)"
MOUTH_SKETCH = "口を入れる穴"


def _items(tl):
    for i in range(tl.count):
        it = tl.item(i)
        try:
            yield it, it.entity
        except Exception:  # タイムラインの一部の項目は実体を返さない
            continue


def _remove_previous(tl, hcomp):
    old = [
        ent
        for _, ent in _items(tl)
        if getattr(ent, "parentComponent", None) == hcomp
        and ent.name.startswith(NOSE_NAME)
    ]
    for ent in reversed(old):
        ent.deleteMe()


def _bar():
    tbm = adsk.fusion.TemporaryBRepManager.get()
    half = (NOSE_LEN / 2 - NOSE_R) / 10
    y, z, r = NOSE_Y / 10, NOSE_Z / 10, NOSE_R / 10
    a = adsk.core.Point3D.create(-half, y, z)
    b = adsk.core.Point3D.create(half, y, z)
    body = tbm.createCylinderOrCone(a, r, b, r)
    for c in (a, b):
        tbm.booleanOperation(body, tbm.createSphere(c, r),
                             adsk.fusion.BooleanTypes.UnionBooleanType)
    box = adsk.core.OrientedBoundingBox3D.create(
        adsk.core.Point3D.create(0, y, -1.0),
        adsk.core.Vector3D.create(1, 0, 0),
        adsk.core.Vector3D.create(0, 1, 0),
        NOSE_LEN / 10 + 1, 2 * r + 1, 2.0,
    )  # Z −2〜0 cm（Z 0 より外を切る）
    tbm.booleanOperation(body, tbm.createBox(box), adsk.fusion.BooleanTypes.IntersectionBooleanType)
    return body


def _cut_shelf(tl, hcomp, front):
    """口の穴の奥の棚を，口の穴の形と「鼻当ての内側より手前」の重なりだけ削る."""
    sk = [ent for _, ent in _items(tl)
          if isinstance(ent, adsk.fusion.Sketch) and ent.name == MOUTH_SKETCH]
    if len(sk) != 1 or sk[0].profiles.count != 1:
        raise RuntimeError(f"「{MOUTH_SKETCH}」の輪郭が 1 つでない")
    sk = sk[0]
    top = sk.transform.translation.z * 10  # 下書きの面の Z（口の穴はここから 5 mm 削る）
    feats = hcomp.features
    ei = feats.extrudeFeatures.createInput(
        sk.profiles.item(0), adsk.fusion.FeatureOperations.NewBodyFeatureOperation)
    ei.startExtent = adsk.fusion.OffsetStartDefinition.create(
        adsk.core.ValueInput.createByReal((-4.0 - top) / 10))
    ei.setDistanceExtent(False, adsk.core.ValueInput.createByReal((SHELF_Z + 4.0) / 10))
    prism = feats.extrudeFeatures.add(ei)
    prism.name = NOSE_NAME + "_棚_口の形"
    tool = prism.bodies.item(0)

    tbm = adsk.fusion.TemporaryBRepManager.get()
    y1 = (NOSE_Y - NOSE_R) / 10
    box = adsk.core.OrientedBoundingBox3D.create(
        adsk.core.Point3D.create(0, (y1 + 4.0) / 2, (SHELF_Z - 4.0) / 20 - 0.05),
        adsk.core.Vector3D.create(1, 0, 0), adsk.core.Vector3D.create(0, 1, 0),
        10.0, y1 - 4.0, abs(SHELF_Z + 4.0) / 10 + 0.3)  # Y 40 mm〜鼻当ての内側
    base = feats.baseFeatures.add()
    base.startEdit()
    hcomp.bRepBodies.add(tbm.createBox(box), base)
    base.finishEdit()
    base.name = NOSE_NAME + "_棚_手前"
    group = adsk.core.ObjectCollection.create()
    group.add(base.bodies.item(0))
    ci = feats.combineFeatures.createInput(tool, group)
    ci.operation = adsk.fusion.FeatureOperations.IntersectFeatureOperation
    feats.combineFeatures.add(ci).name = NOSE_NAME + "_棚_道具"
    group = adsk.core.ObjectCollection.create()
    group.add(tool)
    ci = feats.combineFeatures.createInput(front, group)
    ci.operation = adsk.fusion.FeatureOperations.CutFeatureOperation
    feats.combineFeatures.add(ci).name = NOSE_NAME + "_棚"


def run(_context: str):
    app = adsk.core.Application.get()
    if app.activeDocument.name != "SmTIASv4":
        raise RuntimeError("SmTIASv4 をアクティブにしてから実行する")
    des = adsk.fusion.Design.cast(app.activeProduct)
    tl = des.timeline
    if des.snapshots.hasPendingSnapshot:
        des.snapshots.add()
    hocc = [o for o in des.rootComponent.occurrences if o.component.name == "筐体"][0]
    hcomp = hocc.component
    _remove_previous(tl, hcomp)

    nose = [it for it, ent in _items(tl)
            if isinstance(ent, adsk.fusion.ExtrudeFeature) and ent.name == NOSE_HOLE]
    if len(nose) != 1:
        raise RuntimeError(f"「{NOSE_HOLE}」が見つからない")
    nose[0].isSuppressed = True

    front = [b for b in hcomp.bRepBodies if b.name == "前側"][0]
    _cut_shelf(tl, hcomp, front)
    base = hcomp.features.baseFeatures.add()
    base.startEdit()
    hcomp.bRepBodies.add(_bar(), base)
    base.finishEdit()
    base.name = NOSE_NAME + "_形"
    group = adsk.core.ObjectCollection.create()
    group.add(base.bodies.item(0))
    ci = hcomp.features.combineFeatures.createInput(front, group)
    ci.operation = adsk.fusion.FeatureOperations.JoinFeatureOperation
    hcomp.features.combineFeatures.add(ci).name = NOSE_NAME
    des.computeAll()

    inside = adsk.fusion.PointContainment.PointInsidePointContainment
    for pt, want in (
        ((0, NOSE_Y, -0.3), True),  # 鼻当ての顔の側
        ((12.5, NOSE_Y, NOSE_Z), True),  # 端の丸みの中
        ((0, NOSE_Y, 0.3), False),  # 顔の面より外は無い
        ((0, 50.0, -2.0), False),  # 口の穴は元のまま
        ((0, 54.5, -5.5), False),  # 棚は削った
        ((0, 56.0, -5.0), True),  # 鼻当ての真下の壁は残る
        ((0, 57.0, -15.0), True),  # 鼻の穴は閉じた
    ):
        got = front.pointContainment(adsk.core.Point3D.create(*(v / 10 for v in pt))) == inside
        print("check", pt, "solid" if got else "empty", "OK" if got == want else "NG")
    bb = front.boundingBox
    print("front bbox mm", [round(v * 10, 2) for v in (bb.minPoint.x, bb.minPoint.y, bb.minPoint.z,
                                                      bb.maxPoint.x, bb.maxPoint.y, bb.maxPoint.z)])
    print("front volume cm3", round(front.volume, 2))
