#!/usr/bin/env python3
"""Ambil isi artikel via WP REST by slug + cek HTTP 200 halaman artikel."""
import json, re, subprocess, sys

TARGETS = [
    ("studiosoft", "https://studiosoft.id", "riset-kompetitor-seo"),
    ("uky", "https://studiosoft.id", "landing-page-vs-website-mana-yang-dibuat-dulu"),
    ("tslaw", "https://www.tslaw.id", "panduan-pendirian-pt-untuk-pelaku-usaha"),
    ("tsc", "https://www.theskincodeclinic.com", "kulit-gatal-berkepanjangan-kapan-ke-dokter"),
    ("das", "https://dasindonesia.com", "10-kesalahan-waktu-memilih-mobil-bekas"),
]


def strip_html(h):
    h = re.sub(r"<(script|style)[^>]*>.*?</\1>", " ", h, flags=re.S | re.I)
    h = re.sub(r"<br\s*/?>|</p>", "\n", h, flags=re.I)
    h = re.sub(r"<[^>]+>", "", h)
    h = h.replace("&nbsp;", " ").replace("&#8217;", "'").replace("&#8220;", '"').replace("&#8221;", '"')
    h = h.replace("&amp;", "&").replace("&#8211;", "-").replace("&#8212;", "-").replace("&quot;", '"')
    h = re.sub(r"[ \t]+", " ", h)
    h = re.sub(r"\n{2,}", "\n", h)
    return h.strip()


for acc, base, slug in TARGETS:
    api = f"{base}/wp-json/wp/v2/posts?slug={slug}&_fields=link,title,content,excerpt,date"
    r = subprocess.run(["curl", "-sS", "-m", "60", api], capture_output=True, text=True)
    try:
        arr = json.loads(r.stdout)
    except Exception:
        print(f"### {acc}: GAGAL parse API: {r.stdout[:200]}")
        continue
    if not arr:
        print(f"### {acc}: tidak ada post untuk slug {slug}")
        continue
    p = arr[0]
    link = p["link"]
    code = subprocess.run(
        ["curl", "-sS", "-o", "/dev/null", "-w", "%{http_code}", "-L", "-m", "60",
         "-A", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)", link],
        capture_output=True, text=True).stdout.strip()
    body = strip_html(p["content"]["rendered"])
    print(f"\n############################## {acc} | HTTP {code} | {link}")
    print("JUDUL:", strip_html(p["title"]["rendered"]))
    print(body[:2600])
