#!/usr/bin/env python3
"""Ambil judul + isi artikel (WP REST) untuk menulis caption yang akurat.

Usage: python3 fetch_artikel_isi.py <url> [<url> ...]
"""
import json, re, subprocess, sys, time

URL_RE = re.compile(r"<[^>]+>")


def clean(h):
    h = re.sub(r"<(script|style)[^>]*>.*?</\1>", " ", h, flags=re.S | re.I)
    h = URL_RE.sub(" ", h)
    h = (h.replace("&#8217;", "'").replace("&#8216;", "'").replace("&#038;", "&")
         .replace("&#8211;", "-").replace("&nbsp;", " ").replace("&amp;", "&")
         .replace("&#8220;", '"').replace("&#8221;", '"').replace("&quot;", '"'))
    return re.sub(r"\s+", " ", h).strip()


ts = int(time.time())
for url in sys.argv[1:]:
    p = url.rstrip("/").split("/")
    slug = p[-1]
    root = "/".join(url.split("/")[:3])
    api = "%s/wp-json/wp/v2/posts?slug=%s&_fields=title,link,date,content,excerpt&cb=%d" % (root, slug, ts)
    raw = subprocess.run(["curl", "-4", "-s", "--http1.1", "--max-time", "60", api],
                         capture_output=True, text=True, timeout=90).stdout
    try:
        posts = json.loads(raw)
    except Exception:
        posts = []
    print("=" * 78)
    if not posts:
        print("GAGAL ambil: %s  raw=%s" % (url, raw[:150]))
        continue
    a = posts[0]
    body = clean(a["content"]["rendered"])
    print("URL  : %s" % a["link"])
    print("JUDUL: %s" % clean(a["title"]["rendered"]))
    print("TGL  : %s" % a["date"])
    print("ISI  : %s" % body[:1400])
