#!/usr/bin/env python3
"""依頼158：agg158.py から呼ぶ。2 の (a) 台の前・(b) 依頼と荷物・(c) 患者・(e) 立っている人がよけた回・(f) 採血の所（青の積む所）のまわりの問題"""
import csv, json, os, statistics
from collections import Counter, defaultdict
import trips158 as TP

ROOM = (0.0, 31.0, 22.0, 46.0)        # 内科の処置室（青の積む所の台がある部屋）
FRONT = (0.0, 27.0, 24.0, 31.0)       # その前の外来の大廊下


def rd(run, f):
    return list(csv.DictReader(open(os.path.join(run, f), encoding="utf-8")))


def inr(r, x, z):
    return r[0] - 1e-4 <= x <= r[2] + 1e-4 and r[1] - 1e-4 <= z <= r[3] + 1e-4


def hm(t):
    t = int(round(t)) + 7 * 3600 + 1800
    return "%d:%02d" % (t // 3600, (t % 3600) // 60)


def fl(v):
    return float(v) if v not in ("", None) else None


def handoff(run, s):
    print("(a) 台の前（handoff158.csv。秒）")
    hd = rd(run, "handoff158.csv")
    tr = {r["trip_no"]: r for r in rd(run, "trips.csv")}
    trk = [(float(r["t_s"]), float(r["x"]), float(r["z"])) for r in rd(run, "robot_track.csv")]
    print("   便 道    積む所→届け先          荷物 出発(表)  出た   遅れ  積む人が着く 積む 横に立った 出たのは積み終わりの後 | 着いた  目安(pickup_wait_s) 受け取る人が着く(着いてから) 横に立った 待った秒  動いたか")
    late = []; okL = okD = 0; diffs = []
    for h in hd:
        if not h["start_s"]: print("   便 %s：走っていない" % h["trip_no"]); continue
        ls, le = fl(h["load_start_s"]), fl(h["load_end_s"])
        st = float(h["start_s"]); dl = st - float(h["depart_s"])
        if dl > 0.5: late.append((h["trip_no"], dl))
        after = le is not None and st >= le - 1e-6
        a, rel = fl(h["arrive_dest_s"]), fl(h["release_s"])
        mv = 0.0
        if a is not None and rel is not None:
            ps = [(x, z) for t, x, z in trk if a + 0.6 <= t <= rel - 0.6]
            if ps: mv = max(((x - ps[0][0]) ** 2 + (z - ps[0][1]) ** 2) ** 0.5 for x, z in ps)
        side_l = fl(h["loader_side_s"]); side_u = fl(h["receiver_side_s"])
        if after and side_l is not None and abs(side_l - TP.LOAD_S) < 0.11: okL += 1
        if side_u is not None and abs(side_u - TP.UNLOAD_S) < 0.11 and rel is not None and fl(h["unload_end_s"]) is not None and abs(rel - fl(h["unload_end_s"])) < 0.06 and mv < 0.05: okD += 1
        if h["pickup_wait_actual_s"]: diffs.append(float(h["pickup_wait_actual_s"]) - float(h["pickup_wait_param_s"]))
        print("   %2s %-5s %s→%s %2s  %8.1f %8.1f %5.1f  %8s  %s %6s  %s | %8s  %6s  %8s（%6s） %6s  %7s  %.3f m%s" % (
            h["trip_no"], h["route"], h["from"][:6], h["to"][:6], h["items"], float(h["depart_s"]), st, dl, h["loader_arrive_s"], h["load_start_s"], h["loader_side_s"],
            "はい" if after else "いいえ", h["arrive_dest_s"], h["pickup_wait_param_s"], h["receiver_arrive_s"], h["pickup_wait_actual_s"], h["receiver_side_s"], h["robot_dest_wait_s"], mv,
            ("・" + h["note"]) if h["note"] else ""))
    print("   積む人が load_s 横に立ってから出た便 %d／%d・届け先で受け取る人が unload_s 横に立ち、降ろし終わるまで動かなかった便 %d／%d" % (okL, len(hd), okD, len(hd)))
    if diffs: print("   届け先で受け取る人が着くまでの秒 − 目安（pickup_wait_s）：平均 %+.1f 秒・最小 %+.1f・最大 %+.1f" % (sum(diffs) / len(diffs), min(diffs), max(diffs)))
    print("   出発の遅れ %d 便（計 %.1f 秒・最大 %.1f 秒）：%s" % (len(late), sum(d for _, d in late), max([d for _, d in late] or [0]), "・".join("便 %s %.1f 秒" % x for x in late) or "なし"))
    wl = [float(h["loader_total_s"]) - float(h["loader_side_s"]) for h in hd if h["loader_total_s"]]
    if wl: print("   積む人がロボットを待った秒（台に着いてから積み始めまで）：合計 %.1f・最大 %.1f（%d 便が 0 秒より長い）" % (sum(wl), max(wl), sum(1 for x in wl if x > 0.06)))


def requests(run, s):
    print("(b) 依頼と荷物（params day_schedule.requests_all・trips_all と比べる）")
    rq = TP.requests(run); tp = TP.trips_param(run)
    hd = {r["trip_no"]: r for r in rd(run, "handoff158.csv")}
    byr = Counter(q["route"] for q in rq); urg = sum(1 for q in rq if q["urgent"]); bys = Counter(q["by"] for q in rq)
    print("   依頼 %d 件（緑 %d・青 %d・赤 %d）・至急 %d 件・運んだもの ロボット %d・人 %d" % (len(rq), byr["green"], byr["blue"], byr["red"], urg, bys["robot"], bys["staff"]))
    n = Counter(q["trip"] for q in rq if q["by"] == "robot")
    bad = 0
    for i, t in enumerate(tp):
        h = hd.get(str(i + 1))
        u = h["items"] if h else "?"
        same = str(t["items"]) == u
        if not same: bad += 1
    print("   便ごとの荷物の数：Unity の記録（handoff158 の items）と params の trips_all の items が %d／%d 便で同じ" % (len(tp) - bad, len(tp)))
    print("   便ごとの依頼の数と荷物の数：", "・".join("便%d %d件/%d個%s" % (i + 1, n.get(i, 0), t["items"], "（至急あり）" if any(q["urgent"] and q["trip"] == i for q in rq) else "") for i, t in enumerate(tp)))
    R = TP.Req(run)
    mx = defaultdict(lambda: (0, 0.0)); old = defaultdict(float)
    for k in range(0, int(s["sim_s"]), 5):
        w = R.waiting(float(k))
        for r, (c, cu, o) in w.items():
            if c > mx[r][0]: mx[r] = (c, float(k))
            old[r] = max(old[r], o)
    print("   待っている荷物の数の最大（5 秒ごと）：", "・".join("%s %d 個（%s）・いちばん古い依頼の待ちの最長 %.0f 秒" % (r, mx[r][0], hm(mx[r][1]), old[r]) for r in ("green", "blue", "red")))
    early = []
    for i, t in enumerate(tp):
        h = hd.get(str(i + 1))
        if not h or not h["loader_arrive_s"]: continue
        lr = max([float(q["t"]) for q in rq if q["by"] == "robot" and q["trip"] == i] or [0.0])
        if float(h["load_start_s"] or 1e9) < lr: early.append("便%d（積み始め %s 秒・最後の依頼 %.1f 秒）" % (i + 1, h["load_start_s"], lr))
    print("   積み始めが、その便の最後の依頼より前だった便：", "・".join(early) or "なし")
    ct = TP.clip_trips(run)
    print("   動画2の便：", "・".join("%s 便 %d（%s）" % (k, v[0], v[1]) for k, v in ct.items()))


def steps_of(r):
    out = []
    for x in r["steps"].split("|"):
        p = x.split(":")
        if len(p) >= 5: out.append((p[0], float(p[1]), fl(p[2]), fl(p[3]), p[4]))
    return out


def patients(run, s, run157):
    print("(c) 患者")
    rows = rd(run, "people147.csv")
    pat = [r for r in rows if r["what"] == "外来の患者"]
    blood = [r for r in pat if any(n == "内科の処置室" for n, *_ in steps_of(r))]
    bd = Counter(r["dept"] for r in blood); ad = Counter(r["dept"] for r in pat)
    went = [r for r in blood if any(n == "内科の処置室" and a is not None for n, _, a, _, _ in steps_of(r))]
    print("   採血に行くと決まった外来の患者 %d／%d 人（%.0f%%）・着いた %d 人。科ごと：%s" % (len(blood), len(pat), 100.0 * len(blood) / max(1, len(pat)), len(went),
          "・".join("%s %d／%d" % (d, bd[d], ad[d]) for d in ad)))
    ch = [r for r in rows if r["what"] == "化学療法の患者"]
    print("   化学療法の患者の採血 %d 人" % sum(1 for r in ch if any(n == "内科の処置室" and a is not None for n, _, a, _, _ in steps_of(r))))
    hows = Counter(h for r in pat + ch for n, _, a, _, h in steps_of(r) if n == "内科の処置室" and a is not None)
    print("   内科の処置室での待ち方：", "・".join("%s %d" % kv for kv in hows.items()))
    for lab, rr in (("依頼158", run), ("依頼157", run157)):
        zl = [r for r in rd(rr, "zones147.csv") if r["zone"] == "内科の処置室"]
        pk = max(zl, key=lambda r: (int(r["patients"]), -float(r["t_s"])))
        hrs = defaultdict(list)
        for r in zl: hrs[int(float(r["t_s"]) // 3600)].append(int(r["patients"]))
        print("   %s 内科の処置室にいた患者と付き添い（1分ごと）：最大 %s 人（%s）・1時間ごとの平均 %s" % (lab, pk["patients"], hm(float(pk["t_s"])),
              " ".join("%s %.1f" % (hm(h * 3600)[:-3] + "時", sum(v) / len(v)) for h, v in sorted(hrs.items()))))
    # 外の待合・中待合にいた時間
    ow = [a2 - a for r in pat for n, _, a, a2, _ in steps_of(r) if n == "総合受付・会計の待合" and a is not None and a2 is not None for _ in [0]]
    mw = [a2 - a for r in pat for n, _, a, a2, _ in steps_of(r) if n == "中待合" and a is not None and a2 is not None]
    mwt = [a2 - a for r in pat for n, _, a, a2, _ in steps_of(r) if n == "中待合（処置・検査室を待つ）" and a is not None and a2 is not None]
    skipped_outer = s.get("flow_outer_wait_skipped", 0)
    q = lambda v: "%d 人・中央値 %.1f 分・最短 %.1f・最長 %.1f" % (len(v), statistics.median(v) / 60, min(v) / 60, max(v) / 60) if v else "0 人"
    print("   外の待合（総合受付・会計の待合）で番を待った：%s（外の待合を飛ばした人 %d）" % (q(ow), skipped_outer))
    print("   中待合で診察を待った：%s／中待合で処置・検査室を待った：%s" % (q(mw), q(mwt)))
    m157 = [a2 - a for r in rd(run157, "people147.csv") if r["what"] == "外来の患者" for n, _, a, a2, _ in steps_of(r) if n == "中待合" and a is not None and a2 is not None]
    print("   （依頼157 の中待合：%s）" % q(m157))
    for nm in ("生理検査の待合", "生理検査の検査室", "処置・検査室"):
        v = [a2 - a for r in pat for n, _, a, a2, _ in steps_of(r) if n == nm and a is not None and a2 is not None]
        print("   %s にいた：%s" % (nm, q(v)))
    # 化学療法の患者 20 人
    print("   化学療法の患者 %d 人（行き先の順と、着いた時刻・いた分）：" % len(ch))
    for r in ch:
        st = steps_of(r)
        print("     id %s（付き添い%s）入る %s：%s／出る %s" % (r["id"], "あり" if any(x["lead_id"] == r["id"] for x in rows) else "なし", hm(float(r["spawn_s"])) if r["spawn_s"] else "-",
              " → ".join("%s %s(%s分)" % (n, hm(a) if a is not None else "-", "%.0f" % ((a2 - a) / 60) if a is not None and a2 is not None else "-") for n, _, a, a2, _ in st if n != "正面玄関"),
              hm(float(r["exit_s"])) if r["exit_s"] else "（回の終わりに中）"))
    tl = [x for x in rd(run, "toilet149.csv") if x["what"] == "化学療法の患者"]
    tc = Counter(x["id"] for x in tl)
    print("   化学療法の患者のトイレ：%d 回（1回 %d 人・2回 %d 人）・行き先 %s" % (len(tl), sum(1 for v in tc.values() if v == 1), sum(1 for v in tc.values() if v == 2),
          "・".join("%s %d" % kv for kv in Counter(x["toilet"] for x in tl).items())))
    comp = Counter(r["dept"] for r in rows if r["what"] == "付き添い")
    print("   付き添い（科ごと）：", "・".join("%s %d" % kv for kv in comp.items()))
    # 救急
    er = [r for r in rows if r["what"] == "救急の患者"]
    xr = rd(run, "xray158.csv")
    print("   救急の患者 %d 人（付き添い %d）。X線室の行き来 %d 回（決まった人 %d）：" % (len(er), comp.get("救急", 0), len(xr), sum(1 for r in er if r["toilet_want"] == "1")))
    for x in xr:
        print("     id %s %s ベッドを立つ %s 秒・X線室に着く %s 秒（歩き %.0f 秒）・ベッドに戻る %s 秒（帰り %.0f 秒）" % (x["id"], x["kind"], x["leave_bed_s"], x["arrive_s"],
              float(x["arrive_s"]) - float(x["leave_bed_s"]), x["back_s"], float(x["back_s"]) - float(x["stay_end_s"])))
    for nm in ("救急の待合", "処置ベッド"):
        v = [a2 - a for r in er for n, _, a, a2, _ in steps_of(r) if n == nm and a is not None and a2 is not None]
        print("   救急の患者が %s にいた：%s" % (nm, q(v)))
    vis = [r for r in rows if r["what"] == "見舞いの人"]
    rc = [r for r in vis if any(n.startswith("総合受付") and a is not None for n, _, a, _, _ in steps_of(r))]
    up = [r for r in vis if r["from"] == "正面玄関"]
    print("   見舞いの人 %d 人：玄関から来た %d 人のうち総合受付に寄った %d 人（エレベーターから来た %d 人は寄らない）" % (len(vis), len(up), len(rc), len(vis) - len(up)))
    rhow = Counter(h for r in rc for n, _, a, _, h in steps_of(r) if n.startswith("総合受付"))
    print("   寄った所：", "・".join("%s %d" % kv for kv in rhow.items()))


def yields(run, s):
    y = rd(run, "yield158.csv")
    print("(e) 立っている人が半歩よけた回 %d（戻った %d・戻りきれずに立った %d・自分の行き先へ %d・よける場所が無かった組 %d）" % (
        s.get("flow_yields", 0), sum(1 for r in y if r["end"] == "戻った"), sum(1 for r in y if r["end"] == "戻りきれずに立った"), s.get("flow_yields_cancel", 0), s.get("flow_yield_no_room", 0)))
    print("   よけた人：", "・".join("%s %d" % kv for kv in Counter((r["cat"] + " " + r["no"]).strip() for r in y).most_common()))
    print("   通れなかった人：", "・".join("%s %d" % kv for kv in Counter(r["why"] for r in y).most_common()))
    print("   所：", "・".join("%s %d" % kv for kv in Counter(r["zone"] for r in y).most_common(12)))
    print("   立って待つ点を外せず、外さずに選んだ回（flow_stand_fallback）%d" % s.get("flow_stand_fallback", 0))


def blue_area(run, a, b157):
    print("(f) 採血の人が増えた内科の処置室（青の積む所）の中と前の問題（ロボットの中心の位置。1／2／3／4／5／止まりきれなかった）")
    for lab, x in (("依頼158", a), ("依頼157", b157)):
        c = defaultdict(Counter)
        for e in x["ev"]:
            rx, rz = float(e["robot_x"]), float(e["robot_z"])
            where = "中" if inr(ROOM, rx, rz) else "前" if inr(FRONT, rx, rz) else None
            if where is None: continue
            d = x["legs"][e["leg_id"]]["dir"] if e["leg_id"] in x["legs"] else ""
            c[where + ("・待っている間" if d == "待ち" else "・走っている間")][int(e["type"])] += 1
        print("   %s：%s" % (lab, "／".join("%s %s" % (k, "／".join(str(c[k][t]) for t in range(1, 7))) for k in ("中・走っている間", "中・待っている間", "前・走っている間", "前・待っている間"))))


def all158(run, a, b157, run157):
    s = a["s"]
    print()
    print("==== 依頼158 の確かめ ====")
    handoff(run, s)
    requests(run, s)
    patients(run, s, run157)
    yields(run, s)
    blue_area(run, a, b157)
    print("ほかの階の職員の3つ（出した・出していない）：", s.get("flow_other_floor_split"))
    print("unity_only158 のキー：", list(s.get("unity_only158", {}).keys()))
