#!/usr/bin/env python3
"""依頼312（stills272.py の写し。paths312 を読む・出力の名前を stills312 にした）／依頼272：静止画（各1枚）の時刻とカメラを、依頼269 の回（撮る回と記録が同じ）から選ぶ。

  still_a 引きで2台が拭いているところ（split）：2台とも「清掃」で、同じ引きの所（paths272 の ANCHORS・内側 6 m）に入っている時刻のうち、
          問題（paths272 の問題の区間）から 60 秒より離れていて、続いている間がいちばん長い区間の真ん中。カメラはその引きの所
  still_b 寄りでステージの段差に引っかかったところ（split）：snags の段差（ステージ）の t_s ＋ 5 秒。注視点＝その台
  still_c 寄りで清掃員が呼ばれて来たところ（split）：calls の引っかかりのうち最初の回の、清掃員が着いた t_arrive_s ＋ 3 秒。注視点＝その台
  still_d 控室の前で水を入れ替えているところ（split）：calls の水の最初の回の、清掃員が着いてから終わるまでの真ん中。注視点＝その台
  still_e shared で2台が近づいたところ（shared）：faceoffs のうち、控室の前の置き場の近く（始めの 300 秒）でない最初の回の t_s。注視点＝2台の真ん中

  python3 stills272.py <split の回> <shared の回> <出力フォルダ>
  出力：stills312_split.csv・stills312_shared.csv（-c272CamPath の形）・stills312_split_cams.txt・stills312_shared_cams.txt・stills272.csv（一覧）
"""
import csv, math, os, sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from paths312 import Track, problems, anchors, g, NEAR_DIST, FOV, W, H


def main():
    sp, sh, out = sys.argv[1], sys.argv[2], sys.argv[3]
    res = {"split": [], "shared": []}
    # a
    tr = Track(sp); P = problems(sp); AN = anchors()
    far = lambda t: all(not (p["a"] - 60 <= t <= p["b"] + 60) for p in P)
    best, cur = None, None
    t = 1800.0
    while t <= tr.end:
        ok = None
        if all(tr.state(k, t) == "清掃" for k in tr.ids) and far(t):
            for an in AN:
                x0, x1, z0, z1 = an["rect"]
                if all(x0 + 6 <= tr.raw(k, t)[0] <= x1 - 6 and z0 + 6 <= tr.raw(k, t)[1] <= z1 - 6 for k in tr.ids): ok = an; break
        if ok is not None and cur is not None and cur[2] is ok: cur[1] = t
        else:
            if cur is not None and (best is None or cur[1] - cur[0] > best[1] - best[0]): best = cur
            cur = [t, t, ok] if ok is not None else None
        t += 1.0
    if cur is not None and (best is None or cur[1] - cur[0] > best[1] - best[0]): best = cur
    ta = g((best[0] + best[1]) / 2)
    an = best[2]
    res["split"].append(("still_a", ta, an["tx"], an["tz"], an["dist"], "引きで2台が拭いている（2台とも清掃・同じ引きの所に入っている %.0f〜%.0f 秒の真ん中・引きの所 %s）" % (best[0], best[1], an["name"])))
    # b
    sn = list(csv.DictReader(open(os.path.join(sp, "snags.csv"), encoding="utf-8")))
    s = [r for r in sn if r["kind"] == "stage"][0]
    tb = g(float(s["t_s"]) + 5.0)
    x, z = tr.at(int(s["robot"]), tb)
    res["split"].append(("still_b", tb, x, z, NEAR_DIST, "%s号機がステージの段差に引っかかって止まった（%s 秒に引っかかった 5 秒後・%s）" % (s["robot"], s["t_s"], "清掃員を呼んだ" if s["staff_called"] == "1" else "自然に解ける")))
    # c
    ca = list(csv.DictReader(open(os.path.join(sp, "calls.csv"), encoding="utf-8")))
    c = [r for r in ca if r["kind"] == "引っかかり"][0]
    tc = g(float(c["t_arrive_s"]) + 3.0)
    x, z = tr.at(int(c["robot"]), tc)
    sk = [r for r in sn if r["call"] == c["call"]][0]
    res["split"].append(("still_c", tc, x, z, NEAR_DIST, "%s号機が%sに引っかかって呼んだ清掃員%sが来た（呼んだ %s 秒・着いた %s 秒の 3 秒後）" % (c["robot"], sk["snag_kind"], c["staff"], c["t_call_s"], c["t_arrive_s"])))
    # d
    c = [r for r in ca if r["kind"] == "水"][0]
    td = g((float(c["t_arrive_s"]) + float(c["t_done_s"])) / 2)
    x, z = tr.at(int(c["robot"]), td)
    res["split"].append(("still_d", td, x, z, NEAR_DIST, "控室の前で清掃員%sが%s号機の水を入れ替えている（着いた %s 秒〜終わった %s 秒の真ん中）" % (c["staff"], c["robot"], c["t_arrive_s"], c["t_done_s"])))
    # e
    tr2 = Track(sh)
    fo = [r for r in csv.DictReader(open(os.path.join(sh, "faceoffs.csv"), encoding="utf-8")) if float(r["t_s"]) > 300]
    f = fo[0]
    te = g(float(f["t_s"]))
    (x1, z1), (x2, z2) = tr2.at(int(f["robot_a"]), te), tr2.at(int(f["robot_b"]), te)
    res["shared"].append(("still_e", te, (x1 + x2) / 2, (z1 + z2) / 2, NEAR_DIST, "shared で%s号機と%s号機が近づいて向かい合って止まった（%s 秒・間 %s m・%s号機は%s・%s号機は%s）" % (
        f["robot_a"], f["robot_b"], f["t_s"], f["dist_m"], f["robot_a"], tr2.state(int(f["robot_a"]), te), f["robot_b"], tr2.state(int(f["robot_b"]), te))))
    allrows = []
    for k, rows in res.items():
        rows.sort(key=lambda r: r[1])
        with open(os.path.join(out, "stills312_%s.csv" % k), "w", newline="") as fo_:
            w = csv.writer(fo_); w.writerow(["cam", "t_s", "tx", "tz", "dist"])
            for n, t, x, z, d, what in rows: w.writerow([n, "%.2f" % t, "%.4f" % x, "%.4f" % z, "%.4f" % d])
        with open(os.path.join(out, "stills312_%s_cams.txt" % k), "w") as fo_:
            for n, t, x, z, d, what in rows: fo_.write("%s,30,75,%.4f,%.4f,%.4f,%d,%d,%d\n" % (n, x, z, d, FOV, W, H))
        allrows += [(k,) + r for r in rows]
    with open(os.path.join(out, "stills312.csv"), "w", newline="") as fo_:
        w = csv.writer(fo_); w.writerow(["run", "cam", "t_s", "tx", "tz", "dist", "what"])
        for r in allrows: w.writerow([r[0], r[1], "%.2f" % r[2], "%.4f" % r[3], "%.4f" % r[4], "%.4f" % r[5], r[6]])
    for r in allrows: print(r[0], r[1], r[2], r[6])


if __name__ == "__main__":
    main()
