"""依頼312：報告用の表。(1) 寄りの区間の動画の中の時刻（_meta.csv の行の順＝動画のコマ）を足した一覧 → paths/camspath312_{sp}_wins_video.csv
(2) summary の数と、依頼272 の回（依頼269 の main269＝依頼272 の撮る回と記録が同じ）との場面の数の比べ
  python3 comp312.py"""
import csv, json, os, collections
C = "/Volumes/KIOXIA/r2r2r-data/service_sim/unity/cleaning"
O = C + "/20261126_rec312"
NEW = {"split": C + "/20261126_mall311/runs/chk311a_r2_split_s0", "shared": C + "/20261126_mall311/runs/chk311e_r2_shared_s0"}
OLD = {"split": C + "/20261123_mall269/runs/main269_r2_split_s0", "shared": C + "/20261123_mall269/runs/main269_r2_shared_s0"}
def clock(t):
    s = int(round(t)) + 22 * 3600
    return "%d:%02d:%02d" % (s // 3600 % 24, s // 60 % 60, s % 60)
def vclock(fr):
    s = fr / 25.0
    return "%d:%04.1f" % (s // 60, s % 60)
for sp in ("split", "shared"):
    meta = list(csv.DictReader(open(O + "/paths/camspath312_%s_meta.csv" % sp, encoding="utf-8")))
    ts = [float(r["t_s"]) for r in meta]
    wins = list(csv.DictReader(open(O + "/paths/camspath312_%s_wins.csv" % sp, encoding="utf-8")))
    out = []
    for w in wins:
        a, b = float(w["a_s"]), float(w["b_s"])
        idx = [i for i, r in enumerate(meta) if r["speed"] == "5倍" and a - 1e-6 <= ts[i] <= b + 0.2]
        out.append(dict(no=w["no"], clock_a=clock(a), clock_b=clock(b), video_a=vclock(idx[0]), video_b=vclock(idx[-1] + 1), frame_a=idx[0], frame_b=idx[-1], video_s=w["video_s"], robot=w["robot"], what=w["what"]))
    with open(O + "/paths/camspath312_%s_wins_video.csv" % sp, "w", newline="", encoding="utf-8") as f:
        wr = csv.DictWriter(f, fieldnames=list(out[0].keys())); wr.writeheader(); wr.writerows(out)
    print("== 寄り %s（%d 区間・動画 %s）" % (sp, len(out), vclock(len(meta))))
    for o in out: print(" %s %s〜%s（動画 %s〜%s・%s 秒）%s号機 %s" % (o["no"], o["clock_a"], o["clock_b"], o["video_a"], o["video_b"], o["video_s"], o["robot"], o["what"]))
def counts(run):
    s = json.load(open(run + "/summary.json"))
    sn = list(csv.DictReader(open(run + "/snags.csv", encoding="utf-8")))
    ca = list(csv.DictReader(open(run + "/calls.csv", encoding="utf-8")))
    st = list(csv.DictReader(open(run + "/stalls.csv", encoding="utf-8")))
    fo = list(csv.DictReader(open(run + "/faceoffs.csv", encoding="utf-8")))
    return s, sn, ca, st, fo
for sp in ("split", "shared"):
    print("== summary %s" % sp)
    for nm, run in (("依頼272（main269）", OLD[sp]), ("依頼312（chk311）", NEW[sp])):
        s, sn, ca, st, fo = counts(run)
        print(" %s：status %s・全部拭き終えた %s（%.1f 秒）・回の終わり %s・ロボットの床 %s・人の床 %s" % (nm, s["status"], clock(s["all_done_t_s"]), s["all_done_t_s"], clock(s["end_t_s"]), s["robot_floor_done_t_s"], s["people_floor_done_t_s"]))
        print("   人を呼んだ %d（水 %d・引っかかり %d・立ち往生 %d）・引っかかった %d（呼んだ %d・自然に解けた %d）・立ち往生 %d・向かい合い %d・跳び %d/%d" % (
            s["calls"], s["tank_calls"], s["stuck_calls"], s.get("stall_rescue_calls", 0), s["snags"], s["snags_staff"], s["snags_self"], s["stalls_30s"], s["faceoffs"], s["robot_jumps"], s["person_jumps"]))
        print("   立ち往生の呼び出しの結果:", [c["outcome"] for c in ca if c["kind"] == "立ち往生"], "立ち往生の訳:", [(x["robot"], x["cause"], x["partner"]) for x in st])
        print("   引っかかりの物:", dict(collections.Counter((x["snag_kind"], "呼" if x["staff_called"] == "1" else "自") for x in sn)))
        print("   向かい合いの時台:", dict(collections.Counter(int((float(x["t_s"]) + 22 * 3600) // 3600 % 24) for x in fo)))
        if "no_progress_trips" in s: print("   今の作りの数：止まりの見張り %s・線が空くのを待つ所へ移る %s・線待ち %s 分・切り返し %s 回・すれ違い %s" % (s["no_progress_trips"], s["line_wait_moves"], s["line_wait_min"], s["kiri_count"], s["rect_pass_bys"]))
