#!/usr/bin/env python3
"""Audit hc40 (19 Sep 2026): stok artikel healthcare SS + status pemakaian di Threads/LinkedIn/FB SS."""
import json, os, re, subprocess, sys

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

c = ReplizClient()


def all_docs():
    docs, page = [], 1
    while True:
        d = c.get("/public/schedule?page=%d&limit=100" % page)
        docs.extend(d.get("docs", []))
        if page >= (d.get("totalPages") or 1):
            break
        page += 1
    return docs


docs = all_docs()
print("TOTAL JADWAL REPLIZ:", len(docs))
json.dump(docs, open("/tmp/repliz_all_20260919.json", "w"))


def wp_all():
    posts = []
    for page in range(1, 8):
        r = subprocess.run(["curl", "-s", "--http1.1", "--max-time", "120",
                            "https://studiosoft.id/wp-json/wp/v2/posts?per_page=100&page=%d&_fields=id,date,slug,title,link,categories" % page],
                           capture_output=True, text=True)
        try:
            d = json.loads(r.stdout)
        except Exception:
            break
        if not isinstance(d, list) or not d:
            break
        posts.extend(d)
        if len(d) < 100:
            break
    return posts


posts = wp_all()
print("TOTAL POST WP:", len(posts))
json.dump(posts, open("/tmp/ss_all_posts.json", "w"))
if posts:
    print("10 ARTIKEL TERBARU:")
    for p in sorted(posts, key=lambda x: x["date"], reverse=True)[:10]:
        print("  ", p["date"][:10], p["slug"])

KW = re.compile(r"rumah-?sakit|rs-|klinik|pasien|dokter|kesehatan|medis|apotek|faskes|health|mental|gigi|estetik", re.I)
hc = [p for p in posts if KW.search(p["slug"]) or KW.search(p["title"]["rendered"])]
print("\n=== ARTIKEL HEALTHCARE (%d) ===" % len(hc))


def norm(u):
    return (u or "").split("?")[0].rstrip("/").lower()


used = {}
for label, aid in (("T", ACC.STUDIOSOFT_THREADS), ("LI", ACC.STUDIOSOFT_LINKEDIN), ("FB", ACC.STUDIOSOFT_FB)):
    s = {}
    for d in docs:
        if d.get("accountId") != aid:
            continue
        st = (d.get("status") or "").lower()
        for m in re.findall(r"https?://(?:www\.)?studiosoft\.id/[^\s\)\]\"']+", (d.get("description") or "")):
            k = norm(m)
            s.setdefault(k, set()).add(st)
    used[label] = s

for p in sorted(hc, key=lambda x: x["date"], reverse=True):
    u = norm(p["link"])
    def st(l):
        v = used[l].get(u)
        if not v:
            return "FREE"
        ok = "success" in v
        return ("USED" if ok else "ERR-ONLY") + str(sorted(v))
    print("  %-58s | %s | T:%-28s LI:%-28s FB:%s" % (p["slug"][:58], p["date"][:10], st("T"), st("LI"), st("FB")))
    print("      %s" % p["link"])
