#!/usr/bin/env python3
"""Update backlog SS/uky dgn draf VALID (<=500 char) + cari slot kosong SS/uky terdekat."""
import json, sys, 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))
SLOTS = [5, 8, 11, 14, 17, 20, 23]

today = json.load(open(f"{WS}/threads_content_today.json"))
pick = {a["account"]: a for a in today["accounts"]}

backlog = {
    "_note": ("Draf Threads StudioSoft + @ukyhandoko yang BELUM terpakai (slot 7-harian penuh). "
              "Link belum pernah dipakai di Threads SS/uky. Caption sudah divalidasi <=500 char + "
              "ada link + ajakan komentar. Dipakai untuk slot kosong berikutnya; cek dulu tiap URL "
              "terhadap set URL terpakai (/tmp/threads_used_all.json) sebelum create."),
    "created": "2026-09-14",
    "items": [
        {"account": "studiosoft", "slot": 11,
         "url": "https://studiosoft.id/retainer-digital-marketing/",
         "text": pick["studiosoft"]["text"]},
        {"account": "uky", "slot": 14,
         "url": "https://studiosoft.id/konsultan-ai-surabaya/",
         "text": pick["uky"]["text"]},
    ],
}
for it in backlog["items"]:
    assert len(it["text"]) <= 500, (it["account"], len(it["text"]))
json.dump(backlog, open(f"{WS}/threads_backlog_ss_uky.json", "w"), indent=1, ensure_ascii=False)
print("backlog diperbarui:", [(i["account"], len(i["text"])) for i in backlog["items"]])

# ── cari slot kosong SS/uky terdekat (7 hari ke depan) ──
c = get_client()
pends = []
for p in range(1, 200):
    r = c.get_schedules(page=p, limit=100)
    b = r.get("docs", [])
    if not b:
        break
    pends.extend([d for d in b if (d.get("status") or "").lower() in ("pending", "draft")])
    if len(b) < 100:
        break
now = datetime.now(WIB)
for name, aid in [("studiosoft", ACC.STUDIOSOFT_THREADS), ("uky", ACC.UKY_THREADS)]:
    taken = {(d.get("scheduleAt") or "")[:13] for d in pends if d.get("accountId") == aid}
    found = None
    for day in range(0, 15):
        d0 = (now + timedelta(days=day)).replace(minute=0, second=0, microsecond=0)
        for h in SLOTS:
            cand = d0.replace(hour=h)
            if cand <= now + timedelta(minutes=10):
                continue
            u = cand.astimezone(timezone.utc).strftime("%Y-%m-%dT%H")
            if u not in taken:
                found = cand
                break
        if found:
            break
    print(f"{name}: slot kosong terdekat = {found.strftime('%Y-%m-%d %H:%M WIB') if found else 'TIDAK ADA dlm 15 hari'}")
print("total pending:", len(pends))
