#!/usr/bin/env python3
"""Daftar artikel healthcare/RS/klinik di studiosoft.id + cek pemakaian di Threads SS."""
import json, re, subprocess, sys

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

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:", len(posts))
json.dump(posts, open("/tmp/ss_all_posts.json", "w"))

KW = re.compile(r"rumah-?sakit|rs-|klinik|pasien|dokter|kesehatan|medis|apotek|faskes|health|mental|gigi|estetik|kecantikan", re.I)
hc = [p for p in posts if KW.search(p["slug"]) or KW.search(p["title"]["rendered"])]
print("\n=== ARTIKEL HEALTHCARE/RS/KLINIK (%d) ===" % len(hc))
for p in sorted(hc, key=lambda x: x["date"], reverse=True):
    print("  %s | #%s | %s" % (p["date"][:10], p["id"], p["slug"]))

# link terpakai di Threads SS
docs = json.load(open("/tmp/repliz_all_20260918.json"))
used = set()
for d in docs:
    if d.get("accountId") != ACC.STUDIOSOFT_THREADS:
        continue
    for m in re.findall(r"https?://(?:www\.)?studiosoft\.id/[^\s\)\]\"']+", (d.get("description") or "")):
        used.add(m.rstrip("/.,"))
used_norm = set(u.split("?")[0].rstrip("/").lower() for u in used)

li_used = set()
for d in docs:
    if d.get("accountId") != ACC.STUDIOSOFT_LINKEDIN:
        continue
    for m in re.findall(r"https?://(?:www\.)?studiosoft\.id/[^\s\)\]\"']+", (d.get("description") or "")):
        li_used.add(m.rstrip("/.,").split("?")[0].rstrip("/").lower())

print("\n=== PEMAKAIAN LINK ===")
for p in sorted(hc, key=lambda x: x["date"], reverse=True):
    u = p["link"].rstrip("/").lower()
    print("  %-60s Threads:%s  LinkedIn:%s" % (p["slug"][:60], "USED" if u in used_norm else "FREE",
                                               "USED" if u in li_used else "FREE"))

print("\n=== SEMUA LINK SS DIPAKAI THREADS (%d) ===" % len(used_norm))
for u in sorted(used_norm):
    print("  ", u)
print("\n=== LINK SS DIPAKAI LINKEDIN (%d) ===" % len(li_used))
for u in sorted(li_used):
    print("  ", u)
