#!/usr/bin/env python3
"""
Twitter @ukyhandoko — share artikel studiosoft.id gaya HOT TAKE (FIXED 2 Sep 2026).
Bahas artikel, kasih opini berani/pancing perdebatan, minta komen — bikin rame & gaduh.
Sopan, no SARA/politik/serang kompetitor. Anti-redundant (13 link sudah dipakai).
"""
import sys, json, urllib.request, re
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))
TW = "6a792f0a62caae1e04f57992"
SLOTS = [5, 8, 11, 14, 17, 20, 23]
STATE_FILE = "/home/mantapman/.hermes/profiles/atun/workspace/twitter_uky_ss_state.json"

# Artikel studiosoft.id yang tersedia (dari daftar lengkap) — hot take hooks per topik
ARTIKEL = json.load(open("/tmp/ss_all_articles.json"))

# hook hot-take per topik (fallback generik)
def hot_hook(judul, url):
    tl = judul.lower()
    if "seo" in tl and "lokal" in tl:
        return "Banyak yang bilang SEO lokal itu buang-buang duit. Padahal buat UMKM di kota kamu, ini bedanya antara dapet pelanggan atau nggak. Debat sini 👇"
    if "seo" in tl and "ai" in tl:
        return "Konten AI sekarang bisa masuk page one. Yang bilang SEO mati? Cek dulu fakta di artikel ini. Gue yakin banyak yang bakal salah paham — komen yang jujur ya 👇"
    if "ai" in tl:
        return "AI itu bukan buzzword — tapi kebanyakan orang salah kaprah cara pakainya. Ini artikel yang bakal bikin kamu mikir ulang. Setuju atau nggak? 👇"
    if "website" in tl and ("biaya" in tl or "harga" in tl):
        return "Website murah = website mati? Banyak yang ketipu harga promo. Gue kasih fakta yang jarang dibahas — siap-siap debat 👇"
    if "website" in tl:
        return "Gue heran, masih ada aja yang mikir website cuma pajangan. Ini bukti kalau website itu mesin jualan. Yang nggak setuju, ayo ke sini 👇"
    if "digital marketing" in tl or "social media" in tl or "medsos" in tl:
        return "Digital marketing itu bukan cuma upload foto doang. Banyak yang habis budget tapi nol hasil — dan gue tau kenapa. Komen kalau kamu ngerasa tersindir 👇"
    if "rumah sakit" in tl or "klinik" in tl:
        return "Rumah sakit/klinik masih males go-digital? Di 2026 ini, itu sama aja buang pasien ke kompetitor. Hot take, tapi baca dulu sebelum protes 👇"
    if "umkm" in tl or "bisnis kecil" in tl:
        return "UMKM gak perlu website? Mitos besar. Yang gue liat, justru yang nggak punya online presence makin tertinggal. Debat di komen 👇"
    if "marketing" in tl:
        return "Marketing tanpa data itu cuma nembak gelap. Artikel ini ngebongkar yang jarang dibahas — gue yakin bakal rame komennya 👇"
    return "Ini artikel yang bikin gue mikir: kebanyakan orang salah paham soal ini. Baca dulu, terus kasih pendapat kamu — gue siap debat 👇"

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 10
    st = load_state()
    used = {p["url"] for p in st.get("posted", [])}
    pool = [(t, l) for t, l in ARTIKEL if l not in used and t.strip().lower() != "x"]
    print(f"📰 stok artikel tersisa (belum di Twitter state): {len(pool)} — jadwalkan {min(n, len(pool))}")

    # pending Twitter uky utk slot
    pend = []
    for p in range(1, 60):
        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") == TW and (d.get("status") or "").lower() == "pending":
                pend.append(d)
    taken = {(d.get("scheduleAt") or "")[:13] for d in pend}

    now = datetime.now(WIB)
    day = now.replace(minute=0, second=0, microsecond=0)
    ok = fail = 0
    for i, (judul, url) in enumerate(pool[:n]):
        # cari slot kosong
        slot = None
        for _ in range(21):
            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:
                    slot = cand
                    break
            if slot:
                break
            day += timedelta(days=1)
        if slot is None:
            print("  ⚠️ slot habis")
            break
        taken.add(slot.astimezone(timezone.utc).strftime("%Y-%m-%dT%H"))
        at = slot.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.000Z")

        # Tweet main: hot take (≤280 incl. link)
        hook = hot_hook(judul, url)
        # link t.co dihitung panjang; buat ringkas
        main = f"{hook}\n\n{url}"
        if len(main) > 280:
            # potong hook
            budget = 280 - len(url) - 3
            hook_short = hook[: budget - 1].rsplit(" ", 1)[0] + "…"
            main = f"{hook_short}\n\n{url}"
        replies = [
            {"text": "Baca artikelnya dulu sebelum debat — biar nggak asal ngegas. 😏", "username": ""},
            {"text": "Pernah ngalamin sendiri? Cerita pengalamanmu, paling seru itu. 👇", "username": ""},
        ]
        payload = {
            "accountId": TW,
            "title": f"Uky — {judul[:40]}",
            "description": main,
            "topic": "SEO & Digital Marketing",
            "type": "text",
            "medias": [],
            "scheduleAt": at,
            "replies": 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:
                res = json.load(r)
            ok += 1
            print(f"  ✅ {slot.strftime('%d/%m %H:00')} WIB | {judul[:55]}")
            st["posted"].append({"date": slot.strftime("%Y-%m-%d"), "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"  ❌ {judul[:40]}: {e}")
    print(f"\n📊 Total: {ok} OK, {fail} gagal")

if __name__ == "__main__":
    main()
