#!/usr/bin/env python3
"""
Share artikel studiosoft.id — HANYA ke 3 akun (FIXED 2 Sep 2026, instruksi Bos):
SS-LinkedIn, SS-Threads, UKY-Threads. Berlaku terus (rutin).
Boleh artikel pernah di-share, asal TIDAK berurutan di akun yang sama.
Slot kosong: 05/08/11/14/17/20/23 WIB.
"""
import sys, json, urllib.request
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]
STATE_FILE = "/home/mantapman/.hermes/profiles/atun/workspace/ss_share_state.json"

# HANYA 3 akun (SS-LinkedIn, SS-Threads, UKY-Threads)
ACCS = {
    "6a334c49c5ff4ce3a32259c9": "SS-LinkedIn",
    "6a335b9ec5ff4ce3a3225c2a": "SS-Threads",
    "6a334e89c5ff4ce3a3225a48": "UKY-Threads",
}

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:
            cand = day.replace(hour=h)
            if cand <= now:
                continue
            utc_h = cand.astimezone(timezone.utc).strftime("%Y-%m-%dT%H")
            if utc_h not in taken:
                return cand
        day += timedelta(days=1)
    return None

def caption_for(acc_name, judul, url):
    if acc_name == "SS-LinkedIn":
        head = f"Artikel menarik dari StudioSoft: {judul}. 📖\n\n"
        body = "Topik ini relevan untuk pebisnis yang ingin berkembang lewat digital — kami rangkum poin pentingnya agar mudah dipahami, lengkap dengan langkah praktis yang bisa langsung diterapkan.\n\n"
    elif acc_name == "SS-Threads":
        head = f"Baru baca artikel menarik dari StudioSoft: {judul}. 📖\n\n"
        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.\n\n"
    else:  # UKY-Threads
        head = f"Sering ditanya soal ini, jadi saya tulis di artikel: {judul}. ✍️\n\n"
        body = "Banyak yang belum tahu, padahal ini penting banget untuk bisnis di era sekarang. Saya jelaskan dengan bahasa sederhana biar langsung bisa dipahami dan diterapkan.\n\n"
    return head + body + url + "\n\n" + "Menurut kamu, mana yang paling relate sama kondisi bisnismu? Yuk diskusi di kolom komentar! 👇\n\n" + "#StudioSoft #DigitalMarketing #SEO #BisnisSurabaya #UMKM"

def load_state():
    try:
        with open(STATE_FILE) as f:
            return json.load(f)
    except Exception:
        return {"posted": []}

def main():
    n = int(sys.argv[1]) if len(sys.argv) > 1 else 30
    all_arts = json.load(open("/tmp/ss_all_articles.json"))
    # urutkan: artikel yang belum pernah dijadwalkan batch ini dulu, lalu sisanya (rotasi)
    st = load_state()
    posted_urls = {p["url"] for p in st.get("posted", [])}
    ordered = [(t, l) for t, l in all_arts if l not in posted_urls] + [(t, l) for t, l in all_arts if l in posted_urls]
    # batasi pool supaya tidak langsung repeat habis-habisan; prioritaskan yang belum di state
    fresh_pool = [(t, l) for t, l in all_arts if l not in posted_urls]
    print(f"📰 pool artikel: {len(all_arts)} | sudah di-state: {len(posted_urls)} | baru: {len(fresh_pool)} — jadwalkan {min(n, len(fresh_pool))}")

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

    # last link per akun (anti berurutan) dari pending yang sudah ada
    last_link = {}
    for accid, plist in pend_map.items():
        for d in plist:
            desc = d.get("description") or ""
            for u in desc.split():
                if "studiosoft.id/" in u:
                    last_link[accid] = u.rstrip("/")
                    break

    ACC_LIST = list(ACCS.items())
    ok = fail = 0
    for i, (judul, url) in enumerate(fresh_pool[:n]):
        accid, acc_name = ACC_LIST[i % len(ACC_LIST)]
        if last_link.get(accid) == url.rstrip("/"):
            # pindah ke akun lain yang aman
            switched = False
            for off in range(1, len(ACC_LIST)):
                a2, n2 = ACC_LIST[(i + off) % len(ACC_LIST)]
                if last_link.get(a2) != url.rstrip("/"):
                    accid, acc_name = a2, n2
                    switched = True
                    break
            if not switched:
                print(f"  ⏭️  {judul[:40]} — semua akun sama dgn slot sebelumnya")
                continue
        slot = next_free_slot(pend_map[accid], now, start_day)
        if slot is None:
            continue
        at = slot.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.000Z")
        cap = caption_for(acc_name, judul, url)
        # FIX 5 Sep 2026: replies HANYA untuk Threads. LinkedIn TIDAK support replies
        # (error post-time "Cannot read properties of undefined (reading 'postId')").
        rep = [
            {"text": "Baca sampai habis ya, ada insight menarik di dalamnya. 📖", "username": ""},
            {"text": "Kalau butuh konsultasi, StudioSoft siap bantu. 👍", "username": ""},
        ] if "Threads" in acc_name else []
        payload = {
            "accountId": accid, "title": f"{acc_name} — {judul[:45]}",
            "description": cap, "topic": "Artikel StudioSoft", "type": "text",
            "medias": [], "scheduleAt": at,
            "replies": rep,
        }
        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})
            last_link[accid] = url.rstrip("/")
            st["posted"].append({"date": slot.strftime("%Y-%m-%d"), "acc": acc_name, "judul": judul, "url": url})
            with open(STATE_FILE, "w") as f:
                json.dump(st, f, indent=1, ensure_ascii=False)
        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()
