#!/usr/bin/env python3
"""
Jadwalkan artikel studiosoft.id yang BELUM PERNAH di-share ke akun-akun StudioSoft/Uky.
Aturan Bos (2 Sep 2026): semua artikel wajib pernah di-share; boleh repeat asal TIDAK berurutan.
Target: SS-Threads, SS-FB, SS-LinkedIn, UKY-Threads, UKY-LinkedIn — slot kosong (05/08/11/14/17/20/23 WIB).
"""
import sys, json, urllib.request, hashlib
from datetime import datetime, timedelta, timezone

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

WIB = timezone(timedelta(hours=7))
SLOTS = [5, 8, 11, 14, 17, 20, 23]

ACCS = {
    "6a335b9ec5ff4ce3a3225c2a": "SS-Threads",
    "6a334952c5ff4ce3a3225941": "SS-FB",
    "6a334c49c5ff4ce3a32259c9": "SS-LinkedIn",
    "6a334e89c5ff4ce3a3225a48": "UKY-Threads",
    "6a33ca10c5ff4ce3a322705d": "UKY-LinkedIn",
}

def get_pending_map():
    pend = {k: [] for k in ACCS}
    for p in range(1, 80):
        raw = urllib.request.Request(f"{BASE}/public/schedule?page={p}&limit=100", headers=HEADERS)
        with urllib.request.urlopen(raw, timeout=30) as r:
            docs = json.load(r)["docs"]
        for d in docs:
            if d.get("accountId") in ACCS and (d.get("status") or "").lower() == "pending":
                pend[d.get("accountId")].append(d)
    return pend

def next_free_slot(pend_list, now, start_day):
    day = start_day
    for _ in range(21):
        taken = {(d.get("scheduleAt") or "")[:13] for d in pend_list}
        for h in SLOTS:
            candidate = day.replace(hour=h)
            if candidate <= now:
                continue
            utc_h = candidate.astimezone(timezone.utc).strftime("%Y-%m-%dT%H")
            if utc_h not in taken:
                return candidate
        day += timedelta(days=1)
    return None

def caption_for(acc_name, judul, url, niche_ai=False):
    if acc_name.startswith("SS-"):
        head = "Baru baca artikel menarik dari StudioSoft — " + judul + ". 📖\n\n"
    else:
        head = "Sering ditanya soal ini, jadi saya tulis di artikel: " + judul + ". ✍️\n\n"
    if niche_ai:
        body = "Topik AI memang lagi ramai — tapi yang penting bukan ikut tren, melainkan paham bagaimana memanfaatkannya untuk bisnis. Artikel ini membahasnya dengan bahasa yang mudah dipahami, lengkap dengan langkah praktisnya.\n\n"
    else:
        body = "Masih banyak pebisnis yang belum sadar, padahal ini bisa jadi pembeda antara website yang sepi dan website yang menghasilkan. Poin-poinnya saya rangkum biar kamu tidak perlu baca semuanya — tapi kalau mau detail, langsung klik linknya saja.\n\n"
    link = url + "\n\n"
    diskusi = "Menurut kamu, mana yang paling relate sama kondisi bisnismu? Yuk diskusi di kolom komentar! 👇\n\n"
    tags = "#StudioSoft #DigitalMarketing #SEO #BisnisSurabaya #UMKM"
    return head + body + link + diskusi + tags

def main():
    n = int(sys.argv[1]) if len(sys.argv) > 1 else 40
    # artikel belum pernah di-share
    fresh = json.load(open("/tmp/ss_unshared.json"))
    fresh = [(t, l) for t, l in fresh if t.strip().lower() != "x" and "wp-json" not in l]
    print(f"📰 artikel BELUM di-share: {len(fresh)} — jadwalkan {min(n, len(fresh))}")

    pend_map = get_pending_map()
    now = datetime.now(WIB)
    start_day = now.replace(hour=0, minute=0, second=0, microsecond=0)

    ok = fail = 0
    # rotasi akun supaya merata & tidak berurutan (tiap artikel beda akun dari artikel sebelumnya)
    acc_cycle = list(ACCS.items())
    for i, (judul, url) in enumerate(fresh[:n]):
        accid, acc_name = acc_cycle[i % len(acc_cycle)]
        slot = next_free_slot(pend_map[accid], now, start_day)
        if slot is None:
            print(f"  ⚠️  {acc_name}: tidak ada slot kosong 21 hari")
            continue
        at = slot.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.000Z")
        niche_ai = any(k in judul.lower() for k in ["ai", "artificial", "overview", "chatbot", "agent"])
        cap = caption_for(acc_name, judul, url, niche_ai)
        payload = {
            "accountId": accid, "title": f"{acc_name} — {judul[:45]}",
            "description": cap, "topic": "Artikel StudioSoft", "type": "text",
            "medias": [], "scheduleAt": at,
            "replies": [
                {"text": "Baca sampai habis ya, ada insight menarik di dalamnya. 📖", "username": ""},
                {"text": "Kalau butuh konsultasi, StudioSoft siap bantu. 👍", "username": ""},
            ],
        }
        req = urllib.request.Request(f"{BASE}/public/schedule",
                                     data=json.dumps(payload).encode(),
                                     headers={**HEADERS, "Content-Type": "application/json"})
        try:
            with urllib.request.urlopen(req, timeout=30) as r:
                res = json.load(r)
            ok += 1
            print(f"  ✅ {slot.strftime('%d/%m %H:00')} | {acc_name:12s} | {judul[:50]}")
            pend_map[accid].append({"scheduleAt": at})
        except Exception as e:
            fail += 1
            print(f"  ❌ {acc_name} | {judul[:40]}: {e}")
    print(f"\n📊 Total: {ok} OK, {fail} gagal")

if __name__ == "__main__":
    main()
