# @pixelstomotors の予約を組み直す（2026-11-22 LOG549）
# r2r2r-content の直下で動かす。sns/schedule.json と、@pixelstomotors 行きの投稿文の json を書き換える。
# 実際には、前半（予定表）を1回目に動かし、後半（本文）は json の字下げを保つように直した2回目を動かした。
import json, re
from datetime import datetime, timedelta, timezone

JST = timezone(timedelta(hours=9))
d = json.load(open('sns/schedule.json'))
p = json.load(open('sns/posted.json'))

# 研究の外側の記録（サイト・表紙・図解・動画づくり・アクセス解析・マンガの作り方・事業・法人化・相談）
OUT = {'LOG445', 'LOG447', 'LOG468', 'LOG433', 'LOG469', 'LOG462', 'LOG471', 'LOG472', 'LOG470', 'LOG473',
       'LOG474', 'LOG476', 'LOG493', 'LOG501', 'LOG502', 'LOG507', 'LOG516', 'LOG525', 'LOG513', 'LOG533',
       'LOG536', 'LOG542', 'LOG543', 'LOG547'}


def key(e):
    return e['id'].rsplit('-x', 1)[0]


# 1. 課題地図の単独の投稿と、研究の外側の記録を外す
live = [e for e in d['posts'] if e.get('account') == 'ptm' and e['id'] not in p]
removed = [e['id'] for e in live if e['id'].startswith('ISSUE') or key(e) in OUT]
d['posts'] = [e for e in d['posts'] if e['id'] not in removed]

# 2. ショートと解説動画は YouTube の公開時刻に固定。それ以外を、SO-101（LOG544）を先頭に並べ直す
live = [e for e in d['posts'] if e.get('account') == 'ptm' and e['id'] not in p]
fixed = [e for e in live if e['id'].startswith(('SHORT_', 'VIDEO_'))]
mov = sorted([e for e in live if e not in fixed], key=lambda e: e['post_at'])
mov.sort(key=lambda e: 0 if e['id'] == 'LOG544-x' else 1)

# 固定の投稿がある日の時間帯（昼 n・夜 e）はふさがっている
taken = set()
for e in fixed:
    t = datetime.fromisoformat(e['post_at']).astimezone(JST)
    taken.add((t.date(), 'n' if t.hour < 16 else 'e'))


def slots():
    """11/22（日）の夜だけ例外で使い、そのあとは平日 12:30・19:30、土日 12:30。"""
    day = datetime(2026, 11, 22, tzinfo=JST).date()
    yield day, 'e'
    while True:
        day += timedelta(days=1)
        yield day, 'n'
        if day.weekday() < 5:
            yield day, 'e'


g = slots()
for e in mov:
    while True:
        s = next(g)
        if s not in taken:
            break
    hh, mm = (12, 30) if s[1] == 'n' else (19, 30)
    e['post_at'] = datetime(s[0].year, s[0].month, s[0].day, hh, mm, tzinfo=JST).isoformat()

json.dump(d, open('sns/schedule.json', 'w'), ensure_ascii=False, indent=2)
open('sns/schedule.json', 'a').write('\n')

# 3. 本文のハッシュタグを外す（SO-101 の LOG544 の #LeRobot だけ残す）。一人称の「僕」を「自分」に
d = json.load(open('sns/schedule.json'))
live = [e for e in d['posts'] if e.get('account') == 'ptm' and e['id'] not in p]
changed = 0
for e in live:
    path = e['source']
    raw = open(path).read()
    ind = None
    m = re.match(r'\{\n( +)"', raw)
    if m:
        ind = len(m.group(1))   # 元の json の字下げの幅を保つ
    s = json.loads(raw)
    po = s['posts']
    c = False
    for k in ('x', 'x_template'):   # x_template はショート・動画の文のもと（同期が x を作り直す）
        if k not in po:
            continue
        t = po[k]
        keep = '#LeRobot' if e['id'] == 'LOG544-x' else None
        lines = []
        for l in t.split('\n'):
            toks = re.findall(r'#\S+', l)
            if toks and re.sub(r'#\S+', '', l).strip() == '':
                kept = [x for x in toks if x == keep]
                if kept:
                    lines.append(' '.join(kept))
                continue
            lines.append(re.sub(r'\s*#\S+', '', l) if toks else l)
        n = '\n'.join(lines).rstrip().replace('僕', '自分')
        if n != t:
            po[k] = n
            c = True
    if c:
        changed += 1
        out = json.dumps(s, ensure_ascii=False, indent=ind) + ('\n' if raw.endswith('\n') else '')
        open(path, 'w').write(out)

print('removed', len(removed), 'changed texts', changed)
live = sorted([e for e in d['posts'] if e.get('account') == 'ptm' and e['id'] not in p], key=lambda e: e['post_at'])
print(len(live), live[0]['post_at'], live[-1]['post_at'])
for e in live[:16]:
    print(e['post_at'][5:16], e['id'])
