"""LOG617：so101g（成功50本＋つかみ直し14本で学んだ π0.5）の実機7回の記録を読み、
外したあとに上下をくり返した動き（暴れ）を数える。so101f（成功50本だけ）の30回と並べる。
KIOXIA の記録は読むだけ。使い方: python3 analyze_617.py <so101_Log12 のフォルダ> <出力の json>
"""
import csv
import json
import os
import sys

import numpy as np
import pandas as pd

LOG = sys.argv[1]
OUT = sys.argv[2]
J = ["pan", "lift", "elbow", "wflex", "wroll", "grip"]
FPS = 30


def load(trial):
    d = pd.read_parquet(f"{LOG}/so101/{trial}/data/chunk-000/file-000.parquet")
    a = np.stack(d["action"].values)            # π0.5 の答え（関節の目標）
    s = np.stack(d["observation.state"].values)  # 実際の関節
    x = np.stack(d["ptm.sent"].values)          # 腕に送った値（1コマの上限 5° をかけたあと）
    cid = d["ptm.chunk_id"].values.astype(int)  # 何個目の答えのコマか
    tj = json.load(open(f"{LOG}/so101/{trial}/trial.json"))
    return a, s, x, cid, tj


def reversals(v, th=4.0):
    """値の向きが th 度より大きく逆になった回数"""
    n, ext, dirn = 0, v[0], 0
    for q in v:
        if dirn >= 0 and q < ext - th:
            n += 1; dirn = -1; ext = q
        elif dirn <= 0 and q > ext + th:
            n += 1; dirn = 1; ext = q
        else:
            ext = max(ext, q) if dirn >= 0 else min(ext, q)
    return n


def closes(g):
    """爪の目標が 12 以上から 12 未満に下がったコマ（閉じた所）"""
    return [i for i in range(1, len(g)) if g[i - 1] >= 12 and g[i] < 12]


def chunk_rows(a, s, cid):
    rows = []
    for c in np.unique(cid):
        i = np.where(cid == c)[0]
        rows.append({"chunk": int(c), "frames": int(len(i)), "t": round(i[0] / FPS, 1),
                     "lift": [round(float(a[i[0], 1]), 1), round(float(a[i[-1], 1]), 1)],
                     "elbow": [round(float(a[i[0], 2]), 1), round(float(a[i[-1], 2]), 1)],
                     "wflex": [round(float(a[i[0], 3]), 1), round(float(a[i[-1], 3]), 1)],
                     "grip": [round(float(a[i[0], 5]), 1), round(float(a[i[-1], 5]), 1)],
                     "state_lift": round(float(s[i[0], 1]), 1), "state_elbow": round(float(s[i[0], 2]), 1)})
    return rows


def per_trial(trial):
    a, s, x, cid, tj = load(trial)
    lo = np.array(tj["safe_range"]["lo"]); hi = np.array(tj["safe_range"]["hi"])
    da = np.abs(np.diff(a, axis=0)); dx = np.abs(np.diff(x, axis=0)); trk = np.abs(x[:-1] - s[1:])
    g = a[:, 5]; cl = closes(g)
    net = []
    for c in np.unique(cid):
        i = np.where(cid == c)[0]
        net.append(a[i[-1], 2] - a[i[0], 2])
    net = np.array(net); big = np.abs(net) > 8
    flips = sum(1 for k in range(1, len(net)) if big[k] and big[k - 1] and net[k] * net[k - 1] < 0)
    return {
        "trial": trial, "frames": int(len(a)), "sec": round(len(a) / FPS, 1),
        "model_step_max": np.round(da.max(0), 1).tolist(), "model_step_p99": np.round(np.percentile(da, 99, axis=0), 1).tolist(),
        "sent_step_max": np.round(dx.max(0), 1).tolist(),
        "out_of_safe_lo": (a < lo - 1e-3).sum(0).tolist(), "out_of_safe_hi": (a > hi + 1e-3).sum(0).tolist(),
        "track_err_max": np.round(trk.max(0), 1).tolist(), "track_err_median": np.round(np.median(trk, axis=0), 1).tolist(),
        "reversals_sent": [reversals(x[:, j]) for j in range(6)], "range_sent": np.round(x.max(0) - x.min(0), 0).tolist(),
        "chunks_elbow_flip": int(flips), "chunks_elbow_over8": int(big.sum()), "closes": len(cl),
        "close_min_grip_state_25f": [round(float(s[e:e + 25, 5].min()), 1) for e in cl[:8]],  # 閉じてから25コマの実際の爪の最小（挟めば約11・空なら約1〜4）
        "pan_at_close": [round(float(s[e, 0]), 1) for e in cl[:8]],
        "switch_jump_sent_median": tj.get("switch_jump_sent", {}).get("median"),
        "latency_median_s": tj.get("latency_median_s"), "horizon": tj.get("horizon"),
        "skips_median": float(np.median(tj.get("skips", [0]))),
    }


rows = list(csv.DictReader(open(f"{LOG}/so101_trials.csv")))
out = {"so101g": [], "so101f": [], "summary": {}}
for r in rows:
    m = "so101g" if "so101g" in r["model"] else ("so101f" if "so101f" in r["model"] else None)
    if not m or not os.path.exists(f"{LOG}/so101/{r['trial']}/data/chunk-000/file-000.parquet"):
        continue
    if m == "so101f" and r["result"] not in ("success", "failure"):
        continue
    t = per_trial(r["trial"]); t.update(place=r["place"], result=r["result"], fail_reason=r["fail_reason"])
    out[m].append(t)
for m in ("so101f", "so101g"):
    for res in ("success", "failure"):
        v = [t for t in out[m] if t["result"] == res]
        if not v:
            continue
        sec = sum(t["sec"] for t in v)
        out["summary"][f"{m}_{res}"] = {
            "n": len(v), "sec_total": round(sec), "sec_median": float(np.median([t["sec"] for t in v])),
            "elbow_flips_per_min": round(sum(t["chunks_elbow_flip"] for t in v) / sec * 60, 1),
            "elbow_over8_chunks_per_min": round(sum(t["chunks_elbow_over8"] for t in v) / sec * 60, 1),
            "closes_per_min": round(sum(t["closes"] for t in v) / sec * 60, 1)}
a, s, x, cid, tj = load("so101_20261130_222611")
out["chunks_222611"] = chunk_rows(a, s, cid)
json.dump(out, open(OUT, "w"), ensure_ascii=False, indent=1)
print(json.dumps(out["summary"], ensure_ascii=False, indent=1))
for t in out["so101g"]:
    print(t["trial"], t["place"], t["result"], t["fail_reason"], t["sec"], "秒", "肘の逆向き", t["chunks_elbow_flip"],
          "閉じた", t["closes"], "閉じた所の台座", t["pan_at_close"], "閉じて25コマの実際の爪の最小", t["close_min_grip_state_25f"],
          "1コマの答えの最大", [round(v, 1) for v in t["model_step_max"]], "追従の差の最大", [round(v, 1) for v in t["track_err_max"]])
