"""@pixelstomotors の X の予約を、研究室の回が中心になるよう並べ直す（2026-11-25・LOG579）。

チャットで2回に分けて動かしたもの（分け方を決める → 並べ直す）を、1本にまとめて残したもの。
中身（分け方・枠の決まり・祝日）は、動かしたときと同じ。

使い方（r2r2r-content の一番上で）:
  python3 reorder_ptm_20261125.py

やること
- 11/25 22:30 より後の @pixelstomotors（account: ptm）の X の行を、4つに分ける
    研究室（lab）／研究室以外（other）／マンガ（manga）／マンガのショート（shorts）
  どれにも入らない行は予定表から消す（drop。投稿文の json は消さない）
- 平日の 12:30・19:30 は研究室。ただし火・木の 19:30 は研究室以外
- 土日と祝日は 12:30 にマンガだけ
- ショートは YouTube の公開時刻に固定。その日の同じ時間帯（昼・夜）には何も入れない
"""
import datetime as dt
import json

S = json.load(open("sns/schedule.json"))
posts = S["posts"]
NOW = "2026-11-25T22:30"
JST = "+09:00"


def ptmx(i):
    return i["platform"] == "x" and i.get("account") == "ptm" and i["post_at"] >= NOW


fut = {i["id"][:-2]: i for i in posts if ptmx(i)}

# 研究室：SO-101 の回と、π0.5・学習の考察。並べる順もこのとおり
lab = ["LOG556", "LOG565", "LOG443", "LOG567", "LOG568", "LOG424", "LOG570", "LOG572", "LOG571",
       "LOG576", "LOG566", "LOG545", "LOG529", "LOG438", "LOG441", "LOG575",
       "GUIDE-generalist-ai-gen-1-5", "LOG540"]
# 研究室以外：配膳・病院は数字で答えられる6本だけ。清掃ロボットの3本（560・563・574）は残す
other = ["LOG554", "LOG423", "HAIZEN04", "LOG442", "LOG434", "LOG559", "LOG449", "LOG440", "LOG577",
         "LOG553", "XS06", "LOG477", "LOG481", "LOG498", "LOG509", "LOG538", "LOG541", "LOG459",
         "LOG557", "LOG448", "LOG458", "LOG508", "LOG511", "LOG518", "LOG528", "LOG532", "LOG425",
         "LOG427", "LOG429", "LOG432"]
for k, pos in (("LOG560", 3), ("LOG563", 6), ("LOG574", 9)):
    other.insert(pos, k)
manga = [k for k in sorted(fut, key=lambda k: fut[k]["post_at"]) if k.startswith("MANGA")]
shorts = [k for k in fut if k.startswith("SHORT")]
for k in lab + other:
    assert k in fut, k
drop = [k for k in fut if k not in lab + other + manga + shorts]

# ショートが入っている日の時間帯はふさぐ
blocked = set()
for k in shorts:
    t = fut[k]["post_at"]
    blocked.add((t[:10], "day" if int(t[11:13]) < 17 else "night"))
holidays = {"2027-01-01", "2027-01-11", "2027-02-11", "2027-02-23"}

L, O, M = list(lab), list(other), list(manga)
assign = {}
day = dt.date(2026, 11, 26)
while L or O or M:
    ds, wd = day.isoformat(), day.weekday()
    if wd >= 5 or ds in holidays:
        if M and (ds, "day") not in blocked:
            assign[M.pop(0)] = f"{ds}T12:30:00{JST}"
    else:
        for hm, half in (("12:30", "day"), ("19:30", "night")):
            if (ds, half) in blocked:
                continue
            is_other = wd in (1, 3) and hm == "19:30"   # 火・木の夜は研究室以外
            pool = O if is_other else L
            if pool:
                assign[pool.pop(0)] = f"{ds}T{hm}:00{JST}"
    day += dt.timedelta(days=1)
    if day > dt.date(2027, 6, 30):
        break

new = []
for i in posts:
    if ptmx(i):
        k = i["id"][:-2]
        if k in drop:
            continue
        if k in assign:
            i = dict(i, post_at=assign[k])
    new.append(i)
S["posts"] = new
open("sns/schedule.json", "w").write(json.dumps(S, ensure_ascii=False, indent=2) + "\n")
print("外した", len(drop), sorted(drop))
for k, v in sorted(assign.items(), key=lambda x: x[1]):
    print(v[5:16], k)
