#!/usr/bin/env python3
"""Analisa hc66: (a) artikel terbaru studiosoft.id, (b) jejak & jadwal Threads/FB/LI per artikel HC."""
import json, re, subprocess, sys, os, time
from datetime import datetime, timezone, timedelta
sys.path.insert(0, "/home/mantapman/.hermes/profiles/atun/workspace")
from repliz_client import ReplizClient, ACC

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
OUT = "/tmp/hc66_analisa.json"

HC_SLUGS = [
 "9-contoh-konten-digital-marketing-rumah-sakit-yang-edukatif-dan-tetap-etis",
 "10-channel-digital-marketing-rumah-sakit-yang-wajib-dikelola-di-era-online",
 "7-strategi-digital-marketing-rumah-sakit-untuk-menambah-pasien-setiap-bulan",
 "cara-klinik-kecantikan-di-surabaya-bisa-ditemukan-lebih-cepat-di-google",
 "strategi-seo-terbaik-untuk-klinik-kecantikan-di-surabaya-tingkatkan-pasien-lewat-google",
 "tips-seo-digital-marketing-surabaya-optimasi-local-untuk-klinik-dan-bengkel-lokal",
 "7-aplikasi-mental-health-anak-usia-4-10-tahun-yang-harus-dicoba-orang-tua",
 "pembuatan-website-rumah-sakit",
 "jasa-digital-marketing-rs",
 "jasa-digital-marketing-klinik",
 "panduan-seo-klinik-rumah-sakit",
 "seo-rumah-sakit",
 "digital-marketing-rumah-sakit-indikator",
 "rs-klinik-digital-marketing-2026",
 "google-business-profile-klinik",
]

def jina(path, tries=4):
    url = "https://r.jina.ai/https://studiosoft.id" + path
    for _ in range(tries):
        p = subprocess.run(["curl", "-s", "--max-time", "180", url], capture_output=True, text=True)
        raw = p.stdout or ""
        i = raw.find('[{"id"')
        if i < 0:
            i = raw.find('[{"')
        if i >= 0:
            j = raw.rfind('}]')
            try:
                return json.loads(raw[i:j+2])
            except Exception as e:
                print("parse gagal:", e)
        time.sleep(3)
    return None

print("=== (a) artikel terbaru (per_page=25) ===")
posts = jina("/wp-json/wp/v2/posts?per_page=25&_fields=id,date,slug,link,title")
if posts:
    json.dump(posts, open("/tmp/hc66_posts.json", "w"), indent=1)
    for p in posts:
        t = re.sub(r"&#\d+;", "'", p["title"]["rendered"])
        print(f"  {p['date'][:10]} #{p['id']:>5} {p['slug']}")
else:
    print("  GAGAL fetch posts")

print("\n=== (b) dump jadwal StudioSoft ===")
c = ReplizClient()
docs, page = [], 1
while page < 90:
    d = c.get_schedules(page=page, limit=100)
    ds = d.get("docs", []) if isinstance(d, dict) else d
    if not ds:
        break
    docs += ds
    if len(ds) < 100:
        break
    page += 1
print("total jadwal:", len(docs))
json.dump(docs, open("/tmp/hc66_sched.json", "w"), ensure_ascii=False)

ACCOUNTS = {
    ACC.STUDIOSOFT_THREADS: "THREADS",
    ACC.STUDIOSOFT_LINKEDIN: "LINKEDIN",
    ACC.STUDIOSOFT_FB: "FACEBOOK",
    ACC.STUDIOSOFT_IG: "IG",
}
now = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M")
print("now UTC:", now)

def hits_for(slug):
    pat = re.compile(re.escape(slug))
    res = {"threads": [], "linkedin": [], "facebook": [], "ig": []}
    for d in docs:
        aid = d.get("accountId")
        plat = ACCOUNTS.get(aid)
        if not plat:
            continue
        blob = json.dumps({k: d.get(k) for k in ("title", "description", "topic")}, ensure_ascii=False)
        for m in (d.get("medias") or []):
            blob += " " + (m.get("url") or "")
        if pat.search(blob):
            res[plat.lower()].append((str(d.get("scheduleAt"))[:16], d.get("status"),
                                      d.get("type"), (d.get("_id") or d.get("id"))[:12]))
    return res

print("\n=== jejak per artikel HC (hanya StudioSoft) ===")
summary = {}
for slug in HC_SLUGS:
    h = hits_for(slug)
    thr = sorted(h["threads"])
    li = sorted(h["linkedin"])
    fb = sorted(h["facebook"])
    fut_thr = [x for x in thr if x[0] >= now and x[1] in ("pending", "scheduled", "draft")]
    last_thr = [x for x in thr if x[0] < now]
    fut_fb = [x for x in fb if x[0] >= now and x[1] in ("pending", "scheduled", "draft")]
    last_fb = [x for x in fb if x[0] < now]
    summary[slug] = {"last_thr": last_thr[-1] if last_thr else None,
                     "fut_thr": fut_thr,
                     "last_fb": last_fb[-1] if last_fb else None,
                     "fut_fb": fut_fb,
                     "li_count": len(li), "li_fut": [x for x in li if x[0] >= now]}
    print(f"\n{slug}")
    print("   thr_last:", summary[slug]["last_thr"], "| thr_future:", fut_thr)
    print("   fb_last :", summary[slug]["last_fb"], "| fb_future:", fut_fb)
    print("   LI total:", len(li), "future:", len(summary[slug]["li_fut"]))

json.dump(summary, open(OUT, "w"), indent=1, ensure_ascii=False)
print("\n-> ", OUT)
