import json, re
WS="/home/mantapman/.hermes/profiles/atun/workspace"
docs=json.load(open('/tmp/repliz_dump_hc64.json'))
posts=json.load(open('/tmp/ss_posts_hc64.json'))
T="6a335b9ec5ff4ce3a3225c2a"; LI="6a334c49c5ff4ce3a32259c9"; FB="6a334952c5ff4ce3a3225941"
URLRE=re.compile(r"https?://[^\s\"'<>)\]]*studiosoft\.id[^\s\"'<>)\]]*")
def slugs(d):
    out=set()
    for m in (d.get('medias') or []):
        for u in URLRE.findall(m.get('url') or ''):
            if 'openclaw-img' not in u: out.add(u.split('?')[0].rstrip('/').split('/')[-1].lower())
    for f in ('description','title','topic'):
        for u in URLRE.findall(d.get(f) or ''):
            if 'openclaw-img' not in u: out.add(u.split('?')[0].rstrip('/').split('/')[-1].lower())
    return out

print("=== THREADS upcoming ===")
rows=[d for d in docs if d.get('accountId')==T]
up=sorted([d for d in rows if (d.get('status') or '').lower() in ('pending','scheduled','draft')],key=lambda d:d.get('scheduleAt') or '')
print(" total",len(rows),"upcoming",len(up))
for d in up:
    print("  ",d.get('scheduleAt','')[:19],d.get('type'),'|',(d.get('title') or '')[:40],'|',','.join(sorted(slugs(d)))[:60])

print("\n=== LINKEDIN upcoming ===")
rows=[d for d in docs if d.get('accountId')==LI]
up=sorted([d for d in rows if (d.get('status') or '').lower() in ('pending','scheduled','draft')],key=lambda d:d.get('scheduleAt') or '')
print(" total",len(rows),"upcoming",len(up))
idx={}
for d in rows:
    for s in slugs(d):
        idx.setdefault(s,[]).append(((d.get('scheduleAt') or '')[:16],(d.get('status') or '').lower()))
for d in up:
    print("  ",d.get('scheduleAt','')[:19],'|',(d.get('title') or '')[:44],'|',','.join(sorted(slugs(d)))[:60])

print("\n=== 30 post terbaru vs jadwal LI (semua status) ===")
for p in posts:
    s=p['slug']; ev=sorted(idx.get(s,[]))
    pend=[e for e in ev if e[1] in ('pending','scheduled','draft')]
    print("  %-62s n=%-3d pending=%s last=%s"%(s[:62],len(ev),pend[:2] if pend else '-',ev[-1] if ev else 'BELUM'))

print("\n=== slot Threads 02:00Z kosong (20 hari) ===")
from datetime import datetime, timezone, timedelta
busy=set((d.get('scheduleAt') or '')[:19] for d in docs if d.get('accountId')==T and (d.get('status') or '').lower() in ('pending','scheduled','draft'))
now=datetime.now(timezone.utc)
start=datetime(now.year,now.month,now.day,tzinfo=timezone.utc)
if now.hour>=2: start+=timedelta(days=1)
for day in range(0,20):
    cand=(start+timedelta(days=day)).strftime('%Y-%m-%dT02:00:00')
    if cand not in busy:
        lab=(datetime.fromisoformat(cand)+timedelta(hours=7)).strftime('%d %b %Y 09:00 WIB')
        print("  FREE:",cand,".000Z  (",lab,")"); break

print("\n=== slot FB 12:30Z kosong ===")
busyfb=set((d.get('scheduleAt') or '')[:19] for d in docs if d.get('accountId')==FB and (d.get('status') or '').lower() in ('pending','scheduled','draft'))
now2=datetime.now(timezone.utc)+timedelta(minutes=30); now2n=now2.replace(tzinfo=None)
today=datetime.now(timezone.utc)
for day in range(0,21):
    d0=datetime(today.year,today.month,today.day,tzinfo=timezone.utc)+timedelta(days=day)
    cand="%sT12:30:00"%d0.strftime('%Y-%m-%d')
    if datetime.fromisoformat(cand)<=now2n: continue
    if cand not in busyfb:
        print("  FREE:",cand,".000Z  (",(datetime.fromisoformat(cand)+timedelta(hours=7)).strftime('%d %b %Y 19:30 WIB'),")"); break

print("\n=== slot LI (7-grid 01/04/07/10/13/16Z) kosong ===")
busyli=set((d.get('scheduleAt') or '')[:19] for d in docs if d.get('accountId')==LI and (d.get('status') or '').lower() in ('pending','scheduled','draft'))
now3=datetime.now(timezone.utc)+timedelta(minutes=30); now3n=now3.replace(tzinfo=None)
cands=[]
for day in range(0,25):
    d0=datetime(today.year,today.month,today.day,tzinfo=timezone.utc)+timedelta(days=day)
    for h in (1,4,7,10,13,16):
        dt=d0+timedelta(hours=h)
        if dt.replace(tzinfo=None)<=now3n: continue
        cand=dt.strftime('%Y-%m-%dT%H:%M:%S')
        if cand not in busyli: cands.append(cand)
cands.sort()
for cand in cands[:5]:
    print("  FREE:",cand,".000Z  (",(datetime.fromisoformat(cand)+timedelta(hours=7)).strftime('%d %b %Y %H:%M WIB'),")")
