"""依頼 445: 黒いケーブルの通り道 (輪・うねり) と サーボの撚った線 (3 本). numpy だけ (Blender の中と外の両方で使う).
cable_366 (書き換えない) の chain・world_pt・catmull を使い, look の cable445 の値で作る.

黒いケーブル (cam):
  留め位置 anchors [(geom, 点 mm)] の間を cable_366 と同じ たるみ (rest_mm. 区間ごとに 外向き out (geom, 向き)) でつなぎ,
  loop_at 番目の留め位置で 小さな輪 (半径 loop_r_mm・1 回り. 輪の面 = その geom の 2 つの向き loop_u・loop_v) を 1 つ足す.
  点の数は コマによらず決まった数 (n_pts) に 弧の長さで並べ直す (Blender の曲線の点の数を変えないため).
サーボの線 (wires):
  2 つの留め位置の間を たるみ (rest_mm・外向き out) でつなぎ, 中心の線のまわりに 3 本を撚る (撚りの半径 twist_r_mm・1 回りの長さ pitch_mm).
  線の色の順は look の wire_rgb (赤・白・黒).
"""
import math
import sys
from pathlib import Path

import numpy as np

sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent / "blender"))
import cable_366 as CB  # noqa: E402


def resample(P, n):
    P = np.asarray(P, float)
    s = np.r_[0, np.cumsum(np.linalg.norm(np.diff(P, axis=0), axis=1))]
    t = np.linspace(0, s[-1], n)
    return np.stack([np.interp(t, s, P[:, k]) for k in range(3)], 1)


def sag_pts(geoms, A, rests, outs, gravity, n_sag):
    pts = []
    for i in range(len(A) - 1):
        a, b = A[i], A[i + 1]
        rest = None if rests[i] is None else rests[i] / 1000
        o = np.array([0, 0, -1.0]) * gravity
        if outs[i] is not None:
            o = o + (1 - gravity) * CB.world_dir(geoms, outs[i][0], outs[i][1])
        pts.append([CB.sag_point(a, b, rest, o, t) for t in np.linspace(0, 1, n_sag + 1, endpoint=False)])
    return pts


def cam_line(geoms, c):
    """黒いケーブルの中心の線 (world m. n_pts×3)."""
    A = [CB.world_pt(geoms, g, p) for g, p in c["anchors"]]
    segs = sag_pts(geoms, A, c["rest_mm"], [None if o is None else (o[0], o[1]) for o in c["out"]], c["gravity"], 4)
    pts = []
    for i, s in enumerate(segs):
        if i == c.get("loop_at", -1) and c.get("loop_r_mm", 0) > 0:  # この区間の始め (= 留め位置 i) に輪を 1 つ
            g = c["anchors"][i][0]
            u, v = CB.world_dir(geoms, g, c["loop_u"]), CB.world_dir(geoms, g, c["loop_v"])
            v = v - (v @ u) * u
            v /= max(np.linalg.norm(v), 1e-9)
            r = c["loop_r_mm"] / 1000
            ctr = A[i] + r * u
            for th in np.linspace(0, 2 * math.pi, 13)[:-1]:
                pts.append(ctr - r * (math.cos(th) * u + math.sin(th) * v))
            pts += list(s[1:])
        else:
            pts += list(s)
    pts.append(A[-1])
    return resample(CB.catmull(np.array(pts), 4), c["n_pts"])


def frame_along(P):
    t = np.gradient(P, axis=0)
    t /= np.maximum(np.linalg.norm(t, axis=1, keepdims=True), 1e-12)
    n = np.zeros_like(P)
    ref = np.array([0, 0, 1.0]) if abs(t[0][2]) < 0.9 else np.array([1.0, 0, 0])
    n[0] = np.cross(t[0], ref)
    n[0] /= np.linalg.norm(n[0])
    for i in range(1, len(P)):  # 平行に運ぶ (撚りが 線の曲がりでねじれないように)
        x = n[i - 1] - (n[i - 1] @ t[i]) * t[i]
        n[i] = x / max(np.linalg.norm(x), 1e-12)
    return t, n, np.cross(t, n)


def wire_lines(geoms, w, twist_r_mm, pitch_mm, n_pts):
    """サーボの線 1 つ → 撚った 3 本 (world m. それぞれ n_pts×3)."""
    a, b = CB.world_pt(geoms, *w["a"]), CB.world_pt(geoms, *w["b"])
    s = sag_pts(geoms, [a, b], [w["rest_mm"]], [(w["out"][0], w["out"][1])], w.get("gravity", 0.0), 8)[0]
    C = resample(CB.catmull(np.array(list(s) + [b]), 3), n_pts)
    _, n, bb = frame_along(C)
    arc = np.r_[0, np.cumsum(np.linalg.norm(np.diff(C, axis=0), axis=1))] * 1000
    out = []
    for j in range(3):
        ph = 2 * math.pi * (arc / pitch_mm + j / 3)
        out.append(C + (twist_r_mm / 1000) * (np.cos(ph)[:, None] * n + np.sin(ph)[:, None] * bb))
    return out, C


def all_lines(geoms, cable445, old_cam=None, old_wires=None):
    """(名前, 点, 半径 mm, 種類 cam / wire, 線の番号 (色)). cable445 に cam・wires が無ければ cable_366 の形 (old) を使う."""
    out = []
    if "cam" in cable445:
        c = cable445["cam"]
        out.append(("cam_cable", cam_line(geoms, c), c["radius_mm"], "cam", -1))
    elif old_cam is not None:
        out.append(("cam_cable", old_cam(geoms), CB.CABLE_R_MM, "cam", -1))
    if "wires" in cable445:
        W = cable445["wires"]
        for w in W["list"]:
            ls, _ = wire_lines(geoms, w, W["twist_r_mm"], W["pitch_mm"], W["n_pts"])
            for j, P in enumerate(ls):
                out.append((f"{w['name']}_{j}", P, W["strand_r_mm"], "wire", j))
    return out
