#!/usr/bin/env python3
"""StudioSoft Healthcare Carousel — hc30 "Cara Klinik Kecantikan di Surabaya Bisa Ditemukan Lebih Cepat di Google"
Cron run 6 Sep 2026 (19:00 UTC).

ATURAN BARU (5 Sep, Bos):
- LinkedIn StudioSoft = TEXT dari ARTIKEL — tapi SKIP run ini: LinkedIn SS PENUH 7 slot/hari
  s/d 9 Okt 2026 oleh pipeline artikel (ss_li_artikel_story.py, 282 artikel), dan artikel hc30
  SUDAH punya jadwal text-nya di LinkedIn (18 Sep 23:00 WIB). Nambah = duplikat URL. ⚠️
- Threads + FB: album carousel TETAP OK (aturan lama). IG: jangan sentuh (SSIGSEP jalan sendiri).
"""
import json, os, sys, re
from datetime import datetime, timezone, timedelta

sys.path.insert(0, "/home/mantapman/.hermes/profiles/atun/workspace")
from repliz_client import ReplizClient, ACC
from diskusi_engine import tambahkan_diskusi

c = ReplizClient()

CAROUSEL_DIR = os.path.expanduser("~/.openclaw/workspace-atun/studiosoft_hc30_carousel")
SLIDE_FILES = ["01_cover.png", "02_kenapa.png", "03_isi.png", "04_langkah.png", "05_cta.png"]

ARTICLE_URL = "https://studiosoft.id/cara-klinik-kecantikan-di-surabaya-bisa-ditemukan-lebih-cepat-di-google/"

# TOPIK #30 — state index 29
TOPIC = "Cara Klinik Kecantikan di Surabaya Bisa Ditemukan Lebih Cepat di Google"
HASHTAG_LINE = "#StudioSoft #SEOKlinikKecantikan #GoogleBusinessProfile #DigitalMarketing #HealthcareDigital"

THREADS = tambahkan_diskusi(
    """Klinik kecantikan bisa punya treatment terbaik, tapi kalau tidak muncul saat calon pasien mencari di Google, semuanya sia-sia.

Artikel StudioSoft membahas 5 langkah agar klinik di Surabaya lebih cepat ditemukan: optimasi Google Business Profile, riset kata kunci lokal, website yang cepat, konten edukatif, sampai backlink lokal. Semuanya bisa dimulai bertahap.""",
    platform='threads', industri='klinik', tone='netral', force=True)

FB = tambahkan_diskusi(
    f"""Klinik kecantikan yang hebat pun tidak akan ramai kalau calon pasien tidak bisa menemukannya saat mencari di Google.

Artikel StudioSoft ini merangkum 5 langkah biar klinik di Surabaya muncul lebih cepat: optimasi Google Business Profile, riset kata kunci lokal (misalnya \u201cklinik botox aman Surabaya\u201d), website yang cepat di HP, konten edukatif, sampai backlink dari direktori dan media lokal. Efeknya nyata: salah satu klinik mitra di Surabaya Timur mengalami peningkatan visibilitas hingga 300%.

Baca artikel lengkapnya: {ARTICLE_URL}

{HASHTAG_LINE}""",
    platform='facebook', industri='digital_marketing', tone='sanjungan', force=True)


def find_free_slot(account_ids, max_days=30):
    """Slot :00 WIB pertama yg bebas (6-menit window) di SEMUA account_ids."""
    slots = [5, 8, 11, 14, 17, 20, 23]
    now_wib = datetime.now(timezone(timedelta(hours=7)))
    pending = {aid: set() for aid in account_ids}
    page = 1
    while True:
        d = c.get(f"/public/schedule?page={page}&limit=100")
        docs = d.get("docs", [])
        for s in docs:
            aid = s.get("accountId")
            if aid not in pending:
                continue
            if s.get("status") not in ("pending", "scheduled", "draft"):
                continue
            st = s.get("scheduleAt", "")
            if st:
                pending[aid].add(st[:19])
        if page >= (d.get("totalPages") or 1):
            break
        page += 1

    def occupied(aid, dt_wib):
        for off in range(6):
            u = (dt_wib + timedelta(minutes=off)).astimezone(timezone.utc)
            if u.strftime("%Y-%m-%dT%H:%M:%S") in pending[aid]:
                return True
        return False

    for day in range(max_days + 1):
        day_dt = now_wib + timedelta(days=day)
        for hour in slots:
            cand = datetime(day_dt.year, day_dt.month, day_dt.day, hour, 0,
                            tzinfo=timezone(timedelta(hours=7)))
            if cand <= now_wib + timedelta(minutes=90):
                continue
            if all(not occupied(aid, cand) for aid in account_ids):
                return cand
    return None


def upload_slides():
    urls = []
    for f in SLIDE_FILES:
        p = os.path.join(CAROUSEL_DIR, f)
        u = c.upload_to_wp(p, filename=f"ss_hc30_{f}")
        if not u:
            print(f"GAGAL upload {f}")
            return None
        urls.append(u)
        print(f"OK {f} -> {u.split('/')[-1]}")
    return urls


def verify(urls, slot_utc):
    """Re-list pending akun TH+FB: cari jadwal dgn media ss_hc30_01_cover.jpg."""
    need = urls[0].split("/")[-1]
    hits = []
    page = 1
    while True:
        d = c.get(f"/public/schedule?page={page}&limit=100")
        for s in d.get("docs", []):
            if s.get("accountId") not in (ACC.STUDIOSOFT_THREADS, ACC.STUDIOSOFT_FB):
                continue
            if (s.get("status") or "").lower() != "pending":
                continue
            ms = [m.get("url", "") for m in (s.get("medias") or [])]
            if any(need in m for m in ms):
                hits.append((s.get("accountId"), (s.get("scheduleAt") or "")[:16],
                             (s.get("title") or "")[:45], len(ms)))
        if page >= (d.get("totalPages") or 1):
            break
        page += 1
    print("\nVERIFIKASI jadwal dgn media", need)
    for h in hits:
        print("  ", h)
    return hits


def main():
    wib = datetime.now(timezone(timedelta(hours=7)))
    print(f"Time WIB: {wib.strftime('%Y-%m-%d %H:%M')}")
    print(f"Threads len: {len(THREADS)} (<=500: {len(THREADS) <= 500})")
    if len(THREADS) > 500:
        print("Threads caption > 500 karakter, tolak kirim.")
        return False
    print(f"FB len: {len(FB)}")
    for name, txt in (("Threads", THREADS), ("FB", FB)):
        m = re.findall(r"@\w+", txt)
        if m:
            print(f"⚠️ mention di {name}: {m}")
            return False

    # LinkedIn TIDAK diikutkan (penjelasan di docstring) → cari slot bebas THREADS+FB saja
    slot_wib = find_free_slot([ACC.STUDIOSOFT_THREADS, ACC.STUDIOSOFT_FB])
    if not slot_wib:
        print("TIDAK ADA slot kosong bersama Threads+FB 30 hari — lapor Bos.")
        return False
    slot = slot_wib.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.000Z")
    print(f"Slot kosong Threads+FB: {slot_wib.strftime('%Y-%m-%d %H:%M')} WIB -> UTC {slot}")

    url = upload_slides()
    if not url:
        return False
    # cek URL bisa diakses publik (funnel ingress)
    import urllib.request
    for u in url:
        try:
            with urllib.request.urlopen(urllib.request.Request(u, method="HEAD"), timeout=20) as r:
                code = r.status
        except Exception as e:
            code = f"ERR {e}"
        print(f"  URL {u.split('/')[-1]}: {code}")
    medias = [c.make_media(u, "image", f"slide{i+1}") for i, u in enumerate(url)]

    base_dt = datetime.fromisoformat(slot.replace("Z", "+00:00"))
    r2 = (base_dt + timedelta(minutes=1)).strftime("%Y-%m-%dT%H:%M:%S.000Z")
    r3 = (base_dt + timedelta(minutes=2)).strftime("%Y-%m-%dT%H:%M:%S.000Z")

    results = {}

    # THREADS: album + 2 replies (pola hc19-hc29)
    print("\nTHREADS:")
    try:
        album = c.schedule_album(ACC.STUDIOSOFT_THREADS, THREADS, slot, medias, title=TOPIC)
        pid = album.get("scheduleId") or album.get("_id")
        print(f"  OK Album -> {pid}")
        c.create_schedule(ACC.STUDIOSOFT_THREADS,
            f"Baca selengkapnya: {ARTICLE_URL}\n\nKonsultasi SEO klinik kecantikan:\nwww.studiosoft.id",
            r2, type_="text", replies=[pid])
        c.create_schedule(ACC.STUDIOSOFT_THREADS,
            HASHTAG_LINE,
            r3, type_="text", replies=[pid])
        print("  OK 2 replies")
        results["threads"] = True
    except Exception as e:
        print(f"  GAGAL {e}")
        results["threads"] = False

    # FACEBOOK: album saja, NO replies (pola hc23-hc29)
    print("\nFACEBOOK:")
    try:
        album = c.schedule_album(ACC.STUDIOSOFT_FB, FB, slot, medias, title=TOPIC)
        pid = album.get("scheduleId") or album.get("_id")
        print(f"  OK Album -> {pid}")
        results["fb"] = True
    except Exception as e:
        print(f"  GAGAL {e}")
        results["fb"] = False

    print("\n" + "=" * 50)
    ok = all(results.values())
    print("Semua platform dijadwalkan!" if ok else f"Gagal: {[k for k, v in results.items() if not v]}")

    if ok:
        verify(url, slot)
        state = {"index": 29, "topic": TOPIC,
                 "last_post": wib.strftime("%Y-%m-%d %H:%M")}
        with open(os.path.expanduser("~/.openclaw/workspace-atun/studiosoft_healthcare_state.json"), "w") as f:
            json.dump(state, f)
        print("State updated -> index 29 (hc30)")
    return ok


if __name__ == "__main__":
    sys.exit(0 if main() else 1)
