#!/usr/bin/env python3
"""Cek artikel HC di studiosoft.id: daftar terbaru per kategori + HTTP status kandidat."""
import json
import subprocess
import sys

BASE = "https://studiosoft.id/wp-json/wp/v2"
UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"


def get(url):
    r = subprocess.run(["curl", "-4", "-s", "--max-time", "90", "-A", UA, url],
                       capture_output=True, text=True)
    return json.loads(r.stdout)


def code(url):
    r = subprocess.run(["curl", "-4", "-sIL", "--http1.1", "--max-time", "120", "-A", UA,
                        url, "-o", "/dev/null", "-w", "%{http_code}"],
                       capture_output=True, text=True)
    return (r.stdout or "").strip()


cats = get(BASE + "/categories?per_page=100&_fields=id,name,slug,count")
hc = [c for c in cats if any(k in c["name"].lower() for k in ("kesehatan", "health", "rumah sakit", "klinik"))]
print("KATEGORI HC:", json.dumps(hc, ensure_ascii=False))
ids = [str(c["id"]) for c in hc]

if ids:
    posts = get(BASE + "/posts?per_page=30&categories=" + ",".join(ids) +
                "&_fields=id,date,slug,title,link")
    print("\nARTIKEL HC TERBARU (%d):" % len(posts))
    for p in posts:
        print("%5d %s %-62s %s" % (p["id"], p["date"], p["slug"], p["title"]["rendered"][:60]))

cand = "https://studiosoft.id/jasa-digital-marketing-klinik/"
print("\nHTTP", cand, code(cand))
r = subprocess.run(["curl", "-4", "-s", "--max-time", "90", "-A", UA,
                    BASE + "/posts?slug=jasa-digital-marketing-klinik&_fields=id,date,slug,title,link,content"],
                   capture_output=True, text=True)
d = json.loads(r.stdout)
print("WP:", d[0]["id"] if d else None, d[0]["date"] if d else None)
if d:
    open("/home/mantapman/.hermes/profiles/atun/workspace/_hc72_artikel.json", "w").write(json.dumps(d[0]))
    import re
    txt = re.sub(r"<[^>]+>", " ", d[0]["content"]["rendered"])
    txt = re.sub(r"\s+", " ", txt)
    print("\nKONTEN (%d char):\n%s" % (len(txt), txt[:3500]))
