#!/usr/bin/env python3
"""Cek jadwal Threads 5 akun (13-14 Okt 2026 WIB) + kumpulkan link yang sudah dipakai.

Output:
  /tmp/scheds_1013.json     : semua jadwal dari API
  /tmp/threads_used_all.json: link pernah dipakai per akun (dari SEMUA jadwal + log harian)
"""
import sys, json, re
from datetime import datetime, timedelta, timezone

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
sys.path.insert(0, WS)
from repliz_client import get_client, ACC

WIB = timezone(timedelta(hours=7))
LOG = f"{WS}/log_threads_harian.json"

ACC_MAP = {
    "studiosoft": ACC.STUDIOSOFT_THREADS,
    "uky": ACC.UKY_THREADS,
    "tslaw": ACC.TSLAW_THREADS,
    "tsc": ACC.TSC_THREADS,
    "das": ACC.DAS_THREADS,
}
NAME = {v: k for k, v in ACC_MAP.items()}

c = get_client()
docs = []
for p in range(1, 150):
    r = c.get_schedules(page=p, limit=100)
    b = r.get("docs", [])
    if not b:
        break
    docs += b
    if len(b) < 100:
        break
print("total schedules:", len(docs))
json.dump(docs, open("/tmp/scheds_1013.json", "w"), ensure_ascii=False)


def wib(sa):
    try:
        return datetime.fromisoformat(str(sa).replace("Z", "+00:00")).astimezone(WIB)
    except Exception:
        return None


print("\n=== JADWAL 12-14 OKT 2026 (WIB) untuk 5 akun ===")
for d in sorted(docs, key=lambda x: str(x.get("scheduleAt"))):
    aid = d.get("accountId")
    if aid not in NAME:
        continue
    dt = wib(d.get("scheduleAt"))
    if not dt or dt.strftime("%Y-%m-%d") not in ("2026-10-12", "2026-10-13", "2026-10-14"):
        continue
    desc = (d.get("description") or "").replace("\n", " ")
    print(f"{dt.strftime('%Y-%m-%d %H:%M')} {NAME[aid]:11s} [{d.get('status')}] {d.get('type')} "
          f"id={d.get('_id')} title={d.get('title')!r} topic={d.get('topic')!r} len={len(desc)} "
          f"| {desc[:150]}")

# ── link yang sudah dipakai per akun (SEMUA jadwal + log) ──
log = json.load(open(LOG))
out = {}
for name, aid in ACC_MAP.items():
    used = set()
    for d in docs:
        if d.get("accountId") != aid:
            continue
        blob = " ".join([d.get("description") or "", d.get("title") or ""])
        for u in re.findall(r"https?://[^\s\)\]\"']+", blob):
            used.add(u.rstrip(".,").rstrip("/").lower())
    for _date, accs in (log.get("threads_used_links") or {}).items():
        for it in accs.get(name, []):
            used.add(it["url"].rstrip("/").lower())
    out[name] = sorted(used)
    print(f"\n{name}: {len(used)} URL pernah dipakai")
json.dump(out, open("/tmp/threads_used_all.json", "w"), indent=1, ensure_ascii=False)
print("disimpan /tmp/threads_used_all.json")
