import json
import sys
import urllib.parse
import urllib.request
from collections import Counter, defaultdict

sys.path.insert(0, '/home/mantapman/.hermes/profiles/atun/workspace')
from repliz_client import HEADERS, BASE

ACC = {"6a76a54d62caae1e04f30968": "IG", "6a60101562caae1e04e901ac": "LI",
       "6a3b41d1c5ff4ce3a32753e8": "FB", "6a35f8b7c5ff4ce3a322b2ed": "TH"}
docs, page = [], 1
while True:
    q = urllib.parse.urlencode({"page": page, "limit": 100})
    req = urllib.request.Request(f"{BASE}/public/schedule?{q}", headers=HEADERS)
    with urllib.request.urlopen(req, timeout=90) as r:
        d = json.load(r)
    b = d.get("docs", d.get("data", []))
    docs += b
    if not d.get("hasNextPage") or not b:
        break
    page += 1
rows = [s for s in docs if ACC.get(str(s.get('accountId')))
        and '2026-10-19' <= str(s.get('scheduleAt'))[:10] <= '2026-11-02']
print('jadwal TS Law 19 Okt-2 Nov:', len(rows), Counter(s.get('status') for s in rows))
feed = defaultdict(list)
for s in sorted(rows, key=lambda s: str(s.get('scheduleAt'))):
    a = ACC[str(s.get('accountId'))]
    if s.get('type') == 'story':
        continue
    feed[(str(s.get('scheduleAt'))[:10], a)].append(
        f"{str(s.get('scheduleAt'))[11:16]}Z {s.get('type')}:"
        f"{str((s.get('medias') or [{}])[0].get('url', '')).split('/')[-1][:38]}")
print('== feed per hari (non-story) ==')
for (tgl, a), isi in sorted(feed.items()):
    if tgl in ('2026-10-19', '2026-10-20', '2026-10-21', '2026-10-22'):
        print(' ', tgl, a, ' + '.join(isi))
many = {k: v for k, v in feed.items() if len(v) > 1}
print('hari dengan >1 post feed:', {f"{k[1]} {k[0]}": len(v) for k, v in many.items()})
alb = [s for s in rows if s.get('type') == 'album']
print('album:', len(alb), '| semua media bertipe image:',
      all(all(str(m.get('type')) == 'image' for m in (s.get('medias') or [])) for s in alb))
print('story 20 Okt:', [(ACC[str(s.get('accountId'))], str(s.get('scheduleAt'))[11:16],
                         str((s.get('medias') or [{}])[0].get('url', '')).split('/')[-1])
                        for s in rows if s.get('type') == 'story'
                        and str(s.get('scheduleAt'))[:10] == '2026-10-20'])
