#!/usr/bin/env python3
"""
Jadwalkan artikel studiosoft.id ke akun-akun StudioSoft/Uky (BATCH 2).
Aturan Bos (2 Sep 2026): boleh artikel pernah di-share, asal TIDAK berurutan.
Prioritas: artikel yang belum pernah di-share. Skip link yang sudah terjadwal di akun yang sama.
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]
STATE_FILE = "/home/mantapman/.hermes/profiles/atun/workspace/ss_share_state.json"

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):
    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"
    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"
    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():
    if os_path_exists(STATE_FILE):
        with open(STATE_FILE) as f:
            return json.load(f)
    return {"posted": []}

import os as _os
def os_path_exists(p):
    return _os.path.exists(p)

def main():
    # semua artikel (281) — prioritas belum pernah di-share
    all_arts = json.load(open("/tmp/ss_all_articles.json"))
    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]
    fresh_urls = {l for _, l in fresh}

    # urutkan: yang belum pernah di-share dulu, sisanya setelahnya
    ordered = fresh + [(t, l) for t, l in all_arts if l not in fresh_urls]

    st = load_state()
    posted_urls = {p["url"] for p in st["posted"]}  # sudah dijadwalkan batch ini
    ordered = [(t, l) for t, l in ordered if l not in posted_urls]

    n = int(sys.argv[1]) if len(sys.argv) > 1 else 40
    print(f"📰 pool: {len(ordered)} (fresh {len(fresh)} + pernah-share) — jadwalkan {min(n, len(ordered))}")

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

    # untuk anti-berurutan: catat link terakhir per akun dari jadwal 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

    ok = fail = 0
    ACC_LIST = list(ACCS.items())
    for i, (judul, url) in enumerate(ordered[:n]):
        accid, acc_name = ACC_LIST[i % len(ACC_LIST)]
        # anti-berurutan: link ini tidak boleh sama dengan link terakhir akun tsb
        if last_link.get(accid) == url.rstrip("/"):
            accid2, acc_name2 = ACC_LIST[(i + 3) % len(ACC_LIST)]
            if last_link.get(accid2) != url.rstrip("/"):
                accid, acc_name = accid2, acc_name2
            else:
                print(f"  ⏭️  {acc_name}: {judul[:40]} sama dgn slot sebelumnya — skip")
                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 & FB 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()
