#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""waypoint_streaming_replay.py

teach JSON から抽出した代表姿勢を、ウェイポイント間を線形補間した合成軌道で
連続再生する（drag_teach_v2 の play と同じ送信流儀 = 0.1s 周期ストリーミング）。

waypoint_replay.py（単発/連打方式）でグリッパー後の send_angles が実機に
無視される問題が4回の実機テストで解消できなかった一方、同じ実機で v2 play の
ストリーミングはグリッパー実開閉込みで完走実績がある。よって送信周りは v2 と
同じ流儀でそのまま採用し、ウェイポイント間の補間 pose 列をそこに載せる。

実行シーケンス（waypoint_replay と同じ11 step 構成）:
  STEP  1 先頭移動: send_angles(HOME, SPEED_FIRST) + settle
  STEP  2 GRIPPER open
  STEP  3 MOVE → APPROACH_PICK            (streaming)
  STEP  4 MOVE → PICK                     (streaming)
  STEP  5 GRIPPER close
  STEP  6 MOVE → APPROACH_PICK (lift)     (streaming)
  STEP  7 MOVE → APPROACH_PLACE           (streaming)
  STEP  8 MOVE → PLACE                    (streaming)
  STEP  9 GRIPPER open
  STEP 10 MOVE → APPROACH_PLACE (retreat) (streaming)
  STEP 11 MOVE → HOME                     (streaming)

CLI:
  python3 waypoint_streaming_replay.py path/to/drag_v2_xxxx.json
"""

from __future__ import print_function

import argparse
import math
import sys
import time

from pymycobot.mycobot import MyCobot

# waypoint_replay.py を流用（teach JSON 読み込み・ウェイポイント抽出・
# JOINT_LIMITS・HOME・接続定数・到達確認ヘルパ。レビュー済みのため変更しない）
import waypoint_replay as wr


# ---- 定数 ------------------------------------------------------------------
# 接続・JOINT_LIMITS・HOME・読み耐性は waypoint_replay と同値
SERIAL_PORT = wr.SERIAL_PORT
BAUDRATE = wr.BAUDRATE
HOME_ANGLES = list(wr.HOME_ANGLES)
PHASE_ORDER = wr.PHASE_ORDER

# v2 play と同値（v2 が実機で動いている実績値をそのまま使う）
SPEED_FIRST = 20                  # 先頭姿勢（HOME）へ移動するときの速度
SPEED_PLAY = 30                   # ストリーミング送信時の速度
FIRST_MOVE_SETTLE_SEC = 3.0       # 先頭姿勢に着いたあとの待ち
GRIPPER_SPEED = 50                # set_gripper_state の速度（v2 と同値）
GRIPPER_DWELL_SEC = 1.5           # 把持/離し後の待ち（v2 と同値）
STREAM_INTERVAL_SEC = 0.1         # ストリーミング 1 tick の周期（v2 interval_sec と同値）

# 軌道合成：tick あたり最大 STEP_DEG_PER_TICK° まで進める線形補間。
# 0.1s 周期で 2.0°/tick = 20°/s ≒ waypoint_replay の SPEED=20 相当の速さ。
STEP_DEG_PER_TICK = 2.0

# 区間終端の到達確認（waypoint_replay の到達確認を流用）
ARRIVAL_TOL_DEG = wr.ARRIVAL_TOL_DEG
# 到達ホールド判定の許容差。ARRIVAL_TOL_DEG（=2.0）より緩めて、後半区間で
# max|Δ|≈2.4° 程度の遅れが残るケースを timeout 扱いしないようにする。
HOLD_TOL_DEG = 3.0
ARRIVAL_HOLD_TIMEOUT_SEC = 8.0
ARRIVAL_POLL_SLEEP = 0.3
GET_ANGLES_RETRY = wr.GET_ANGLES_RETRY
GET_ANGLES_RETRY_SLEEP = wr.GET_ANGLES_RETRY_SLEEP

# 先頭移動の急加速確認しきい値
FIRST_MOVE_WARN_DEG = wr.FIRST_MOVE_WARN_DEG


# ---- ヘルパ ----------------------------------------------------------------
def _format_angles(a):
    return wr._format_angles(a)


def _build_segments(waypoints):
    """STEP 2 以降の実行列を返す。
    各要素：
      {"kind": "move", "from_name", "to_name", "from", "to", "n_steps", "max_delta"}
      {"kind": "gripper", "action": "open"|"close"}
    STEP 1（current → HOME）は v2 流儀の単発送信＋settle で扱うので含めない。
    """
    HOME = list(HOME_ANGLES)
    AP = list(waypoints["APPROACH_PICK"])
    PK = list(waypoints["PICK"])
    APL = list(waypoints["APPROACH_PLACE"])
    PL = list(waypoints["PLACE"])

    # critical=True の区間は、終端到達が確認できないと次工程（gripper）の
    # 開閉位置がずれるため、到達確認タイムアウト時に ABORT する。
    # STEP 4（PICK 到達 → 直後 close）と STEP 8（PLACE 到達 → 直後 open）のみ critical。
    seq = []
    seq.append({"kind": "gripper", "action": "open"})                                                                                          # STEP 2
    seq.append({"kind": "move", "from_name": "HOME",            "to_name": "APPROACH_PICK",            "from": HOME, "to": AP,   "critical": False})  # STEP 3
    seq.append({"kind": "move", "from_name": "APPROACH_PICK",   "to_name": "PICK",                     "from": AP,   "to": PK,   "critical": True})   # STEP 4
    seq.append({"kind": "gripper", "action": "close"})                                                                                         # STEP 5
    seq.append({"kind": "move", "from_name": "PICK",            "to_name": "APPROACH_PICK (lift)",     "from": PK,   "to": AP,   "critical": False})  # STEP 6
    seq.append({"kind": "move", "from_name": "APPROACH_PICK",   "to_name": "APPROACH_PLACE",          "from": AP,   "to": APL,  "critical": False})  # STEP 7
    seq.append({"kind": "move", "from_name": "APPROACH_PLACE",  "to_name": "PLACE",                   "from": APL,  "to": PL,   "critical": True})   # STEP 8
    seq.append({"kind": "gripper", "action": "open"})                                                                                          # STEP 9
    seq.append({"kind": "move", "from_name": "PLACE",           "to_name": "APPROACH_PLACE (retreat)", "from": PL,   "to": APL,  "critical": False})  # STEP 10
    seq.append({"kind": "move", "from_name": "APPROACH_PLACE",  "to_name": "HOME",                    "from": APL,  "to": HOME, "critical": False})  # STEP 11

    for s in seq:
        if s["kind"] != "move":
            continue
        max_d, _ = wr._max_axis_diff(s["to"], s["from"])
        n_steps = max(1, int(math.ceil(max_d / STEP_DEG_PER_TICK)))
        s["max_delta"] = max_d
        s["n_steps"] = n_steps
    return seq


def _interpolate(a, b, n_steps):
    """a から b への線形補間点を n_steps 個（i=1..n_steps）返す。
    両端の凸結合なので、JOINT_LIMITS 内の a と b なら全点 JOINT_LIMITS 内。"""
    result = []
    for i in range(1, n_steps + 1):
        t = float(i) / float(n_steps)
        pose = [a[k] + (b[k] - a[k]) * t for k in range(6)]
        result.append(pose)
    return result


def _validate_endpoints(seq):
    """全 move 区間の from / to + HOME を JOINT_LIMITS で一括検査。違反があれば True。"""
    has_violation = False
    # HOME 単体
    viol = wr._check_joint_limits(HOME_ANGLES)
    if viol:
        has_violation = True
        print("[WPSR] [ABORT] JOINT_LIMITS 違反: HOME (pose={})".format(HOME_ANGLES))
        for axis, v, lo, hi in viol:
            print("  j{}: value={:.3f} not in [{:.1f}, {:.1f}]".format(axis + 1, v, lo, hi))

    for i, s in enumerate(seq):
        if s["kind"] != "move":
            continue
        for label, pose in (("from", s["from"]), ("to", s["to"])):
            viol = wr._check_joint_limits(pose)
            if viol:
                has_violation = True
                print("[WPSR] [ABORT] JOINT_LIMITS 違反: seg #{} {} ({} side, pose={})".format(
                    i + 1, s["from_name"] + "→" + s["to_name"], label, pose))
                for axis, v, lo, hi in viol:
                    print("  j{}: value={:.3f} not in [{:.1f}, {:.1f}]".format(
                        axis + 1, v, lo, hi))
    return has_violation


def _print_plan(current, seq):
    print("=" * 78)
    print("[WPSR] 実行プラン（v2 play 流儀の補間ストリーミング）")
    print("=" * 78)

    max_d0, _ = wr._max_axis_diff(HOME_ANGLES, current)
    print("  [STEP  1] MOVE → HOME (single send + settle)  speed={}".format(SPEED_FIRST))
    print("            current = {}".format(_format_angles(current)))
    print("            to HOME = {}".format(_format_angles(HOME_ANGLES)))
    print("            max |Δ| = {:.2f}°  (settle {:.1f}s)".format(max_d0, FIRST_MOVE_SETTLE_SEC))

    step_no = 2
    total_ticks = 0
    n_grippers = 0
    for s in seq:
        if s["kind"] == "gripper":
            n_grippers += 1
            state = 0 if s["action"] == "open" else 1
            print("  [STEP {:>2}] GRIPPER {}  set_gripper_state({}, {}) + sleep({:.1f}s)".format(
                step_no, s["action"].upper(), state, GRIPPER_SPEED, GRIPPER_DWELL_SEC))
        else:
            print("  [STEP {:>2}] MOVE → {}  segment {} → {}".format(
                step_no, s["to_name"], s["from_name"], s["to_name"]))
            print("            from    = {}".format(_format_angles(s["from"])))
            print("            to      = {}".format(_format_angles(s["to"])))
            print("            max |Δ| = {:.2f}°  n_steps = {}  (~ {:.1f}s @ {}s/tick)".format(
                s["max_delta"], s["n_steps"],
                s["n_steps"] * STREAM_INTERVAL_SEC, STREAM_INTERVAL_SEC))
            total_ticks += s["n_steps"]
        step_no += 1

    stream_time = total_ticks * STREAM_INTERVAL_SEC
    gripper_time = n_grippers * GRIPPER_DWELL_SEC
    total = FIRST_MOVE_SETTLE_SEC + stream_time + gripper_time
    print("=" * 78)
    print("[WPSR] 合計 ticks = {}, 想定所要時間 ≈ {:.1f}s".format(total_ticks, total))
    print("[WPSR]   内訳: 先頭 settle {:.1f}s + 補間 {:.1f}s + gripper {:.1f}s".format(
        FIRST_MOVE_SETTLE_SEC, stream_time, gripper_time))
    print("=" * 78)


def _hold_until_arrival(mc, target, label):
    """target を最後に送った後、HOLD_TOL_DEG 内に入るまで最大 ARRIVAL_HOLD_TIMEOUT_SEC ポーリング。
    タイムアウトでも ABORT せず WARN のみで戻る（送信を止める方が空中ホールドで危険）。
    """
    t0 = time.time()
    last_max = None
    while time.time() - t0 < ARRIVAL_HOLD_TIMEOUT_SEC:
        actual = wr._get_angles_retry(mc)
        if actual is None:
            time.sleep(ARRIVAL_POLL_SLEEP)
            continue
        max_d, _ = wr._max_axis_diff(actual, target)
        last_max = max_d
        if max_d <= HOLD_TOL_DEG:
            print("[WPSR] arrival OK ({}, max|Δ|={:.2f}° <= tol {:.1f}°)".format(
                label, max_d, HOLD_TOL_DEG))
            return True
        time.sleep(ARRIVAL_POLL_SLEEP)
    print("[WPSR] [WARN] arrival timeout ({}, max|Δ|={:.2f}° > tol {:.1f}°, {:.1f}s)".format(
        label, last_max if last_max is not None else float("nan"),
        HOLD_TOL_DEG, ARRIVAL_HOLD_TIMEOUT_SEC))
    return False


# ---- 実行 ------------------------------------------------------------------
def run(in_path):
    # 1. teach JSON 読み込み + ウェイポイント抽出（waypoint_replay と同じロジック）
    payload, angles, phases, gripper_events, count = wr._load_teach(in_path)
    waypoints, sources = wr._extract_waypoints(angles, phases, gripper_events, count)

    print("[WPSR] 入力ファイル: {}".format(in_path))
    print("[WPSR] 抽出ウェイポイント:")
    for name in PHASE_ORDER:
        print("  {:<14} <- {}".format(name, sources[name]))
        print("  {:<14}    angles = {}".format("", _format_angles(waypoints[name])))

    seq = _build_segments(waypoints)

    if _validate_endpoints(seq):
        print("[WPSR] [ABORT] 違反があるため送信せず終了します")
        sys.exit(1)
    print("[WPSR] JOINT_LIMITS 一括検証 OK（全 endpoint + HOME）")

    # 2. 接続 + power_on
    print("[WPSR] mechArm（MyCobot）へ接続します")
    print("[WPSR] [SAFETY] 再生中はグリッパーが実機で開閉します。爪に指を挟まないこと。")
    mc = MyCobot(SERIAL_PORT, BAUDRATE)
    try:
        po_ret = mc.power_on()
        print("[WPSR] power_on() 完了 result={}".format(po_ret))
        if po_ret is not None and po_ret != 1:
            print("[WPSR] [WARN] power_on 戻り値が None でも 1 でもない: {}".format(po_ret))
    except Exception as e:
        print("[WPSR] [WARN] power_on で例外: {}".format(e))

    # 3. 現在姿勢取得 + プラン表示 + Enter（必要なら yes）
    print("[WPSR] 現在姿勢を取得します（最大 {} 回・{}s 間隔リトライ）".format(
        GET_ANGLES_RETRY, GET_ANGLES_RETRY_SLEEP))
    current = wr._get_angles_retry(mc)
    if current is None:
        print("[WPSR] [ABORT] 現在姿勢が取得できません（リトライ全敗）")
        sys.exit(1)
    print("[WPSR] 現在姿勢 = {}".format(_format_angles(current)))

    first_max_diff, _ = wr._max_axis_diff(HOME_ANGLES, current)
    print("[WPSR] 先頭移動（current → HOME）: max |Δ| = {:.2f}°".format(first_max_diff))

    _print_plan(current, seq)

    print("[WPSR] 周囲に手・物が無いか確認してください。OK なら Enter で開始")
    try:
        input()
    except EOFError:
        print("[WPSR] [ABORT] stdin EOF")
        sys.exit(1)

    if first_max_diff > FIRST_MOVE_WARN_DEG:
        print("[WPSR] [WARN] 先頭移動の最大軸差 {:.2f}° > {:.1f}°。急加速の可能性があります".format(
            first_max_diff, FIRST_MOVE_WARN_DEG))
        print("[WPSR] 続行するには 'yes' と入力してください（それ以外は中止）")
        try:
            ans = input().strip()
        except EOFError:
            print("[WPSR] [ABORT] stdin EOF")
            sys.exit(1)
        if ans != "yes":
            print("[WPSR] 中止しました（差分が大きいため）")
            sys.exit(1)

    # 4. 再生本体（v2 play と同じ try/except KeyboardInterrupt/finally 構成）
    t_start = time.time()
    try:
        # set_fresh_mode(1)（v2 と同じ）
        try:
            mc.set_fresh_mode(1)
            print("[WPSR] set_fresh_mode(1)（最新コマンド優先）")
        except Exception as e:
            print("[WPSR] [WARN] set_fresh_mode(1) で例外: {}".format(e))

        # STEP 1: 先頭姿勢（HOME）へ単発送信 + settle（v2 と同じ流儀）
        print("[STEP  1] MOVE → HOME  send_angles(HOME, {})".format(SPEED_FIRST))
        try:
            res_first = mc.send_angles(HOME_ANGLES, SPEED_FIRST)
            print("[STEP  1]   send_angles result={}".format(res_first))
        except Exception as e:
            print("[WPSR] [WARN] 先頭姿勢 send_angles で例外: {}".format(e))
        print("[STEP  1] {:.1f}s 待ちます（settle）".format(FIRST_MOVE_SETTLE_SEC))
        time.sleep(FIRST_MOVE_SETTLE_SEC)

        # STEP 2 以降: 補間 pose 列を 0.1s 周期で流す + gripper を間に挟む
        step_no = 2
        for s in seq:
            if s["kind"] == "gripper":
                action = s["action"]
                state = 1 if action == "close" else 0
                print("[STEP {:>2}] GRIPPER {} → set_gripper_state({}, {})".format(
                    step_no, action.upper(), state, GRIPPER_SPEED))
                try:
                    mc.set_gripper_state(state, GRIPPER_SPEED)
                except Exception as e:
                    print("[WPSR] [WARN] set_gripper_state で例外: {}".format(e))
                print("[STEP {:>2}] gripper dwell {}s（v2 play と同値）".format(
                    step_no, GRIPPER_DWELL_SEC))
                time.sleep(GRIPPER_DWELL_SEC)
                step_no += 1
                continue

            # move: 線形補間 n_steps tick を STREAM_INTERVAL_SEC 周期で send_angles
            print("[STEP {:>2}] MOVE → {}  segment {} → {}  ({} ticks @ {}s, speed={})".format(
                step_no, s["to_name"], s["from_name"], s["to_name"],
                s["n_steps"], STREAM_INTERVAL_SEC, SPEED_PLAY))
            poses = _interpolate(s["from"], s["to"], s["n_steps"])
            for k, pose in enumerate(poses):
                try:
                    ret = mc.send_angles(pose, SPEED_PLAY)
                except Exception as e:
                    print("[WPSR] [WARN] send_angles で例外 tick={}/{}: {}".format(
                        k + 1, s["n_steps"], e))
                    ret = None
                if ret is not None and ret != 1:
                    # 戻り値はログ注記のみ・abort しない（v2 と同じ）
                    pass
                time.sleep(STREAM_INTERVAL_SEC)

            # 区間終端の到達確認（同期点）。
            # critical=True（次が gripper の区間）はタイムアウトで ABORT。
            # それ以外は WARN のみで続行（v2 play には無いが安全側で実施）。
            arrived = _hold_until_arrival(
                mc, s["to"], "{} → {}".format(s["from_name"], s["to_name"]))
            if not arrived and s.get("critical"):
                print("[WPSR] [ABORT] critical 区間（次は gripper）で到達確認タイムアウト。"
                      "未到達のまま開閉しません。送信を停止します")
                sys.exit(1)
            step_no += 1

        elapsed = time.time() - t_start
        print("=" * 78)
        print("[WPSR] 完了。elapsed = {:.2f}s".format(elapsed))
        print("[WPSR] power はそのまま維持します（release_all_servos は呼びません）")
        print("=" * 78)
    except KeyboardInterrupt:
        # 異常時は新しい送信をやめて終了。mc.stop() は呼ばない（指示通り）。
        print("\n[WPSR] [INTERRUPT] Ctrl-C 検出。新しい送信を停止します（mc.stop は呼びません）")
    finally:
        # set_fresh_mode(0) は正常・異常いずれでも実行（v2 と同じ try/finally）
        try:
            mc.set_fresh_mode(0)
            print("[WPSR] set_fresh_mode(0) 完了")
        except Exception as e:
            print("[WPSR] [WARN] set_fresh_mode(0) で例外: {}".format(e))


def main():
    ap = argparse.ArgumentParser(
        description="teach JSON からウェイポイント間を補間してストリーミング再生（v2 play 流儀）",
    )
    ap.add_argument(
        "in_path",
        help="teach JSON のパス（drag_v2_*.json または drag_v2_*_with_pos.json）",
    )
    args = ap.parse_args()
    run(args.in_path)


if __name__ == "__main__":
    main()
