"""依頼 399 の 1: closes_399.json (explore_399.py が作る) を数えて表にする (numpy だけ. system の python3 で動く).
→ so101/check_399/result_399_part1.json と 画面の表 (REPORT の 1 に写す)

分け方 (つかめなかった閉じ 1 つずつ. 上から順に当てはめる):
  固定側 = 閉じる前 1 秒の 固定側の爪とブロックの最小 ≤ 0 mm (乗った・押した)
  高い   = 閉じる 10 コマの間の 爪と机の最小 > HIGH_MM (机まで下りずに閉じた. 依頼 379 の 成功 −4.2〜−0.1・高すぎ +1.5〜+6.6)
  どちらでもない = そのほか (うち 動く爪がブロックに重なった・水平に 15 mm より離れた を別に数える)
数えるのは 失敗の回の 近く (水平 50 mm 以内) の閉じ全部. ただし so101g 3 回目 (失敗の番号 3 = 持ち上げで落とす) の最後の閉じ (つかんだ) は除く
"""
import json
from collections import Counter, defaultdict
from pathlib import Path

import numpy as np

HERE = Path(__file__).resolve().parent
HIGH_MM = 1.0
FAR_MM = 15.0


def cat(c):
    if c["fixed_block_min"] <= 0:
        return "固定側"
    if c["jaw_table_min_10"] > HIGH_MM:
        return "高い"
    return "どちらでもない"


def r1(x):
    return None if x is None else round(float(x), 1)


def main():
    d = json.loads((HERE / "closes_399.json").read_text())
    out = {"high_mm": HIGH_MM, "far_mm": FAR_MM, "models": {}}
    for model in ("so101f", "so101g"):
        T = [t for t in d["trials"] if t["model"] == model]
        rows = []
        for t in T:
            if t["result"] != "failure":
                continue
            cl = list(t["closes"])
            if t["fail_reason"] == "3" and cl and cl[-1]["kind"] == "held":
                cl = cl[:-1]
            for c in cl:
                horiz = float(np.hypot(c["rel"][0], c["rel"][1]))
                rows.append({"n": t["n"], "place": t["place"], "fail_reason": t["fail_reason"], "kind": c["kind"], "cat": cat(c),
                             "moving_over": c["moving_block_min"] <= 0, "far": horiz > FAR_MM,
                             "jaw_table": c["jaw_table_min_10"], "fixed": c["fixed_block_min"], "moving": c["moving_block_min"],
                             "right": c["rel"][0], "fwd": c["rel"][1], "z": c["rel"][2], "closed_frames": c["closed_frames"],
                             "rise_1s_mm": c["rise_1s_mm"]})
        places = {}
        for p in range(1, 6):
            tp = [t for t in T if t["place"] == p]
            rp = [r for r in rows if r["place"] == p]
            cc = Counter(r["cat"] for r in rp)
            other = [r for r in rp if r["cat"] == "どちらでもない"]
            places[p] = {"trials": len(tp), "success": sum(t["result"] == "success" for t in tp), "closes": len(rp),
                         "固定側": cc["固定側"], "高い": cc["高い"], "どちらでもない": cc["どちらでもない"],
                         "other_moving_over": sum(r["moving_over"] for r in other), "other_far": sum(r["far"] and not r["moving_over"] for r in other),
                         "jaw_table_med": r1(np.median([r["jaw_table"] for r in rp])) if rp else None,
                         "fixed_med": r1(np.median([r["fixed"] for r in rp])) if rp else None,
                         "right_med": r1(np.median([r["right"] for r in rp])) if rp else None,
                         "fwd_med": r1(np.median([r["fwd"] for r in rp])) if rp else None,
                         "closed_frames_med": r1(np.median([r["closed_frames"] for r in rp if r["closed_frames"] is not None])) if rp else None}
        # 失敗の回ごとに いちばん多い分け方 (同じ数なら 固定側 > 高い > どちらでもない)
        per_trial = defaultdict(list)
        for r in rows:
            per_trial[r["n"]].append(r["cat"])
        order = ["固定側", "高い", "どちらでもない"]
        trial_cat = {n: max(order, key=lambda k: (v.count(k), -order.index(k))) for n, v in per_trial.items()}
        # 成功の回の つかんだ閉じ (比べる相手)
        held = []
        for t in T:
            if t["result"] == "success":
                h = [c for c in t["closes"] if c["kind"] == "held"]
                if h:
                    held.append({"n": t["n"], "place": t["place"], "jaw_table": h[-1]["jaw_table_min_10"], "fixed": h[-1]["fixed_block_min"],
                                 "moving": h[-1]["moving_block_min"], "closed_frames": h[-1]["closed_frames"]})
        out["models"][model] = {"rows": rows, "places": places, "trial_cat": trial_cat, "count": dict(Counter(r["cat"] for r in rows)),
                                "success_held": held}
        print(f"\n## {model}  失敗の回の閉じ {len(rows)}  {dict(Counter(r['cat'] for r in rows))}  回ごと {dict(Counter(trial_cat.values()))}")
        print("| 場所 | 成功 / 回 | 閉じ | 固定側 | 高い | どちらでもない (動く爪が重なる・15 mm より離れた) | 爪と机 中央値 | 固定側とブロック 中央値 | 右 / 奥 中央値 | 閉じていたコマ 中央値 |")
        for p, v in places.items():
            print(f"| {p} | {v['success']} / {v['trials']} | {v['closes']} | {v['固定側']} | {v['高い']} | {v['どちらでもない']} ({v['other_moving_over']}・{v['other_far']}) | "
                  f"{v['jaw_table_med']} | {v['fixed_med']} | {v['right_med']} / {v['fwd_med']} | {v['closed_frames_med']} |")
        hj = [h["jaw_table"] for h in held]
        hf = [h["fixed"] for h in held]
        if held:
            print(f"成功 {len(held)} 回のつかんだ閉じ: 爪と机 {np.median(hj):.1f} [{min(hj):.1f}〜{max(hj):.1f}]・固定側 {np.median(hf):.1f} [{min(hf):.1f}〜{max(hf):.1f}]"
                  f"  同じ分け方: {dict(Counter(cat({'fixed_block_min': h['fixed'], 'jaw_table_min_10': h['jaw_table']}) for h in held))}")
            out["models"][model]["success_cat"] = dict(Counter(cat({"fixed_block_min": h["fixed"], "jaw_table_min_10": h["jaw_table"]}) for h in held))
    # 1-2: so101g の閉じ と つかみ直しのお手本の空の閉じ
    demo = d["demo"]
    place_of = {0: 1, 1: 1, 2: 1, 3: 2, 4: 2, 5: 2, 6: 3, 7: 3, 8: 3, 9: 4, 10: 4, 11: 4, 12: 5, 13: 5, 14: 5}   # 依頼 377 の割り振り (3 本ずつ)
    dm = defaultdict(list)
    for x in demo:
        dm[place_of[x["plan_index"]]].append({"plan_index": x["plan_index"], "kind": x["recover"]["kind_ja"], "right": r1(x["rel_state"][0]),
                                              "fwd": r1(x["rel_state"][1]), "z": r1(x["rel_state"][2]), "jaw_table": r1(x["jaw_table"]),
                                              "closed_frames": x["closed_frames"], "rise_1s_mm": x["rise_1s_mm"]})
    g = [r for r in out["models"]["so101g"]["rows"]]
    f = [r for r in out["models"]["so101f"]["rows"]]
    out["demo_by_place"] = dm
    cf = lambda rs: [r["closed_frames"] for r in rs if r["closed_frames"] is not None]  # noqa: E731
    out["closed_frames"] = {"so101g": cf(g), "so101f": cf(f), "demo": [x["closed_frames"] for x in demo]}
    print("\n閉じていたコマ: so101g", np.median(cf(g)), min(cf(g)), max(cf(g)), " so101f", np.median(cf(f)), min(cf(f)), max(cf(f)),
          " お手本", [x["closed_frames"] for x in demo])
    print("1 秒で上がった mm: so101g", np.median([r["rise_1s_mm"] for r in g]), " so101f", np.median([r["rise_1s_mm"] for r in f]),
          " お手本", np.median([x["rise_1s_mm"] for x in demo]))
    for p in range(1, 6):
        print(f"場所{p} お手本:", [(x["kind"], x["right"], x["fwd"], x["z"]) for x in dm[p]])
        print(f"       so101g:", [(r["n"], r1(r["right"]), r1(r["fwd"]), r1(r["z"]), r["closed_frames"]) for r in g if r["place"] == p])
    (HERE / "result_399_part1.json").write_text(json.dumps(out, ensure_ascii=False, indent=1, default=str) + "\n")
    print("[WROTE]", HERE / "result_399_part1.json")


if __name__ == "__main__":
    main()
