#!/usr/bin/env python3
"""
Isi slot kosong Threads uky & StudioSoft dgn ARTIKEL studiosoft.id (link) — FOKUS GROWTH.
Caption ≤500 char (pangkas_threads.batasi): hook + nilai + link + ajakan.
"""
import sys, json, os, re, urllib.request, ssl
from datetime import datetime, timedelta, timezone
sys.path.insert(0, "/home/mantapman/.openclaw/workspace-atun")
from repliz_client import HEADERS, BASE, get_client
from pangkas_threads import batasi

WIB = timezone(timedelta(hours=7))
SLOTS = [5, 8, 11, 14, 17, 20, 23]
UKY = "6a334e89c5ff4ce3a3225a48"
SS = "6a335b9ec5ff4ce3a3225c2a"
STATE = "/home/mantapman/.openclaw/workspace-atun/threads_artikel_growth_state.json"

ctx = ssl.create_default_context(); ctx.check_hostname = False; ctx.verify_mode = ssl.CERT_NONE

def wp_articles():
    out = []
    for p in range(1, 8):
        try:
            req = urllib.request.Request(f"https://studiosoft.id/wp-json/wp/v2/posts?per_page=50&page={p}&_fields=link,title",
                                         headers={'User-Agent': 'Mozilla/5.0'})
            with urllib.request.urlopen(req, timeout=25, context=ctx) as r:
                posts = json.loads(r.read())
        except Exception:
            break
        if not posts:
            break
        out.extend([(x['title']['rendered'], x['link'].rstrip('/')) for x in posts if x['title']['rendered'].strip().lower() != 'x'])
        if len(posts) < 50:
            break
    return out

def hook(judul):
    tl = judul.lower()
    if "ai" in tl or "overview" in tl:
        return f"Saya baca artikel ini soal {judul.lower()} — dan ini yang jarang dibahas orang. 🤖"
    if "seo" in tl:
        return f"Ini penjelasan {judul.lower()} yang paling gampang dipahami. Cek poinnya. 🔍"
    if "website" in tl:
        return f"Soal {judul.lower()} — banyak yang salah kaprah. Ini penjelasannya. 🌐"
    if "social media" in tl or "konten" in tl:
        return f"Kalau kamu bingung soal {judul.lower()}, artikel ini bantu banget. 📱"
    if "klinik" in tl or "rumah sakit" in tl:
        return f"Khusus untuk sektor kesehatan: {judul.lower()}. 🏥"
    return f"Baru baca artikel ini: {judul.lower()} — layak banget buat kamu yang jalanin bisnis. 📖"

def caption_for(judul, url, who):
    h = hook(judul)
    body = f"Judul lengkapnya: {judul}"
    if who == "uky":
        diskusi = "Menurut kamu, bagian mana yang paling relevan buat bisnismu? Cerita di komentar! 👇"
    else:
        diskusi = "Gimana pendapat kamu soal ini? Yuk diskusi di komentar! 👇"
    tags = "#studiosoft #seo #digitalmarketing #bisnissurabaya" if who == "ss" else "#seo #digitalmarketing #bisnis #ai"
    return f"{h}\n\n{body}\n\n{url}\n\n{diskusi}\n\n{tags}"

def get_pending(accid):
    out = []
    for p in range(1, 90):
        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") == accid and (d.get("status") or "").lower() == "pending":
                out.append(d)
    return out

def main():
    n_per = int(sys.argv[1]) if len(sys.argv) > 1 else 40
    arts = wp_articles()
    print(f"📰 artikel tersedia: {len(arts)}")
    st = json.load(open(STATE)) if os.path.exists(STATE) else {"uky": [], "ss": []}

    # artikel yang sudah dipakai di Threads kedua akun
    c = get_client()
    used_links = set()
    docs = []
    for p in range(1, 90):
        r = c.get_schedules(page=p, limit=100)
        docs.extend(r['docs'])
    for d in docs:
        if d.get('accountId') in (UKY, SS):
            desc = d.get('description') or ''
            for m in re.finditer(r'https?://(?:www\.)?studiosoft\.id/\S+', desc):
                used_links.add(m.group(0).rstrip('.,;!?)').rstrip('/'))

    for accid, who, key in [(UKY, "uky", "uky"), (SS, "ss", "ss")]:
        pend = get_pending(accid)
        taken = set()
        for d in pend:
            at = d.get("scheduleAt") or ""
            try:
                dt = datetime.fromisoformat(at.replace("Z", "+00:00")).astimezone(WIB)
                taken.add(dt.strftime("%Y-%m-%d %H"))
            except Exception:
                continue
        used_state = set(st.get(key, []))
        avail = [(t, l) for t, l in arts if l not in used_links and l not in used_state]
        print(f"\n=== {who} | artikel belum dipakai: {len(avail)} | isi maks {n_per} ===")
        day = datetime.now(WIB).replace(minute=0, second=0, microsecond=0)
        count = 0
        for judul, url in avail:
            if count >= n_per:
                break
            slot = None
            for _ in range(20):
                for h in SLOTS:
                    cand = day.replace(hour=h)
                    if cand <= datetime.now(WIB):
                        continue
                    if cand.strftime("%Y-%m-%d %H") not in taken:
                        slot = cand
                        break
                if slot:
                    break
                day += timedelta(days=1)
            if slot is None:
                print("  ⚠️ slot habis")
                break
            taken.add(slot.strftime("%Y-%m-%d %H"))
            at = slot.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.000Z")
            cap = batasi(caption_for(judul, url, who))
            payload = {
                "accountId": accid, "title": f"{who} — {judul[:40]}",
                "description": cap, "topic": "Artikel StudioSoft", "type": "text",
                "medias": [], "scheduleAt": at, "replies": [],
            }
            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:
                    json.load(r)
                count += 1
                st.setdefault(key, []).append(url)
                print(f"  ✅ {slot.strftime('%d/%m %H:00')} | {judul[:45]}")
            except Exception as e:
                print(f"  ❌ {judul[:35]}: {e}")
        with open(STATE, "w") as f:
            json.dump(st, f, indent=1, ensure_ascii=False)
        print(f"  → {who}: {count} terjadwal")

if __name__ == "__main__":
    main()
