#!/usr/bin/env python3
"""hc44: scan SEMUA slug WP yang bertema healthcare + jejaknya di LI/FB/Threads SS."""
import json, re, subprocess, sys
WS = "/home/mantapman/.hermes/profiles/atun/workspace"
sys.path.insert(0, WS)
from repliz_client import ACC

posts = []
for page in range(1, 4):
    r = subprocess.run(["curl", "-s", "--http1.1", "--max-time", "150",
                        "https://studiosoft.id/wp-json/wp/v2/posts?per_page=100&page=%d&_fields=date,slug,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)
print("total post:", len(posts))

KW = re.compile(r"klinik|rumah-sakit|kesehatan|pasien|dokter|medis|apotek|gigi|kecantikan|mental|sehat|rs-", re.I)
hc = [(p["date"][:10], p["slug"], p["categories"]) for p in posts if KW.search(p["slug"])]
print("kandidat healthcare:", len(hc))

docs = json.load(open('/tmp/repliz_all_20260923.json'))
url_re = re.compile(r'studiosoft\.id/([a-z0-9\-]+)')
ACCID = {"T": ACC.STUDIOSOFT_THREADS, "L": ACC.STUDIOSOFT_LINKEDIN, "F": ACC.STUDIOSOFT_FB}


def cell(aid, s):
    tr = []
    for d in docs:
        if d.get("accountId") != aid:
            continue
        t = " ".join([(d.get("description") or ""), (d.get("title") or "")])
        if s in url_re.findall(t):
            tr.append(((d.get("scheduleAt") or "")[:10], d.get("status")))
    tr.sort()
    if not tr:
        return "FREE"
    ok = sum(1 for x in tr if x[1] == "success")
    pend = [x for x in tr if x[1] in ("pending", "scheduled", "draft")]
    err = sum(1 for x in tr if x[1] == "error")
    if pend:
        return "ok%d pend%d(%s)" % (ok, len(pend), pend[0][0])
    return "ok%d err%d last%s" % (ok, err, tr[-1][0])


print("%-11s %-56s %-18s %-20s %s" % ("DATE", "SLUG", "THREADS", "LINKEDIN", "FACEBOOK"))
for date, s, cats in sorted(hc):
    flag = "*" if 1042 in (cats or []) else " "
    print("%s%s %-56s %-18s %-20s %s" % (date, flag, s[:56], cell(ACCID["T"], s),
                                         cell(ACCID["L"], s), cell(ACCID["F"], s)))
