#!/usr/bin/env python3
"""Verifikasi lima draf klaster rumah sakit StudioSoft: skema, gambar, tautan, kebersihan teks."""
import base64, json, re, urllib.request

AUTH = base64.b64encode(b"bambangbot:q26r RePo BVy6 pwU2 F3z7 ouyl").decode()
H = {"Authorization": f"Basic {AUTH}", "User-Agent": "Mozilla/5.0"}
UA = {"User-Agent": "Mozilla/5.0"}
DRAF = [9406, 9409, 9412, 9415, 9418]
INDUK = "9-contoh-konten-digital-marketing-rumah-sakit"


def rest(p):
    return json.loads(urllib.request.urlopen(urllib.request.Request("https://studiosoft.id" + p, headers=H), timeout=180).read())


tujuan = set()
print("=== lima draf ===")
for pid in DRAF:
    x = rest(f"/wp-json/wp/v2/posts/{pid}?context=edit")
    isi = x["content"]["raw"]
    teks = re.sub(r"\s+", " ", re.sub("<[^>]+>", " ", re.sub(r"<script.*?</script>", " ", isi, flags=re.S))).strip()
    fm = x.get("featured_media")
    uk = fmt = "-"
    if fm:
        m = rest(f"/wp-json/wp/v2/media/{fm}")
        uk = f"{m['media_details'].get('width')}x{m['media_details'].get('height')}"
        fmt = m["source_url"].split(".")[-1]
    tautan = re.findall(r'href="(https://studiosoft\.id/[^"]+)"', isi)
    tujuan.update(tautan)
    cjk = len(re.findall(r"[\u4e00-\u9fff\u3040-\u30ff\uac00-\ud7af]", teks))
    harga = len(re.findall(r"(Rp\s?[\d]|\bdiskon\s+\d+\s?%)", teks))
    patah = 0
    for mo in re.finditer(r"<(p|li|h2|h3)[^>]*>(.*?)</\1>", isi, re.S):
        b = mo.group(2)
        if "\n" not in b or "<br" in b:
            continue
        for t2 in [q.strip() for q in b.split("\n")][:-1]:
            if t2 and not re.search(r"[.!?:;]$", t2):
                patah += 1
    print(f"\n■ #{pid} [{x['status']}] {x['slug']}")
    print(f"   kata {len(teks.split())} · meta fokus '{x['meta'].get('_yoast_wpseo_focuskw')}' "
          f"judul {len(x['meta'].get('_yoast_wpseo_title') or '')} desc {len(x['meta'].get('_yoast_wpseo_metadesc') or '')}")
    print(f"   gambar {uk} .{fmt} · alt {'ada' if fm else 'TIDAK'} · WA {'ada' if 'wa.me/6281935000624' in isi else 'TIDAK'} · "
          f"FAQPage {'ada' if 'FAQPage' in isi else 'TIDAK'} · h2 {isi.count('<h2')} · faq {isi.count('<h3>')}")
    print(f"   CJK {cjk} · harga {harga} · baris terpotong {patah} · tautan internal {len(set(tautan))}")
    print(f"   tautan balik ke induk: {'ADA' if INDUK in isi else 'TIDAK'}")

print("\n=== semua tujuan tautan: apakah hidup? ===")
for u in sorted(tujuan):
    try:
        with urllib.request.urlopen(urllib.request.Request(u, headers=UA), timeout=45) as x:
            st = x.status
    except Exception as e:
        st = str(e)[:34]
    print(f"   {st} · {u.replace('https://studiosoft.id', '')}")
