#!/usr/bin/env python3
"""Kuantifikasi spam judi di klinikmetamorf.com: jumlah, tanggal, penulis, sitemap, plugin."""
import base64, html, json, re, time, urllib.request, urllib.error
from collections import Counter

SITE = "https://klinikmetamorf.com"
UA = {"User-Agent": "Mozilla/5.0"}
AUTH = base64.b64encode(b"bambangbot:whWA hVlW omQk 9FSL 8rkz VMHy").decode()


def wp(path):
    r = urllib.request.Request(SITE + path, headers={"Authorization": f"Basic {AUTH}", **UA})
    for _ in range(4):
        try:
            with urllib.request.urlopen(r, timeout=120) as x:
                return json.loads(x.read())
        except urllib.error.HTTPError as e:
            return {"__err": e.code}
        except Exception:
            time.sleep(3)
    return {"__err": "gagal"}


print("=== SEMUA post (publish) ===")
posts, page = [], 1
while True:
    d = wp(f"/wp-json/wp/v2/posts?per_page=100&page={page}&context=edit&_fields=id,title,date,slug,link,author,status")
    if not isinstance(d, list):
        break
    posts += d
    if len(d) < 100:
        break
    page += 1
print(f"total post: {len(posts)}")

SPAM = re.compile(r"kasyn|slot|judi|togel|spins|pragmatic|gacor|bet\b|bonus|kasino|online casino|sitzung|wypłacaln|sportsbook|rtp|gambling", re.I)
spam = [p for p in posts if SPAM.search(html.unescape(p["title"]["rendered"]))]
bersih = [p for p in posts if p not in spam]
print(f"  terindikasi spam judi : {len(spam)}")
print(f"  sisanya (konten klinik): {len(bersih)}")

if spam:
    tgl = sorted(p["date"][:10] for p in spam)
    print(f"  rentang tanggal spam  : {tgl[0]} → {tgl[-1]}")
    print("  penulis:", dict(Counter(p.get("author") for p in spam)))
    print("\n  10 judul spam terbaru:")
    for p in sorted(spam, key=lambda x: x["date"], reverse=True)[:10]:
        print(f"    {p['date'][:10]} | #{p['id']} author={p.get('author')} | {html.unescape(p['title']['rendered'])[:62]}")

print("\n=== kategori & tag (indikasi injeksi) ===")
cats = wp("/wp-json/wp/v2/categories?per_page=100&_fields=id,name,count")
if isinstance(cats, list):
    for c in sorted(cats, key=lambda x: -x["count"])[:10]:
        print(f"  kat {c['id']:>5} {html.unescape(c['name'])[:42]:<44} {c['count']} post")

print("\n=== plugin aktif ===")
plug = wp("/wp-json/wp/v2/plugins?_fields=name,status,plugin")
if isinstance(plug, list):
    for p in plug:
        if p.get("status") == "active":
            print(f"  AKTIF: {p['name']} | {p['plugin']}")
else:
    print("  ", plug)

print("\n=== sitemap: apakah spam ikut terdaftar? ===")
try:
    r = urllib.request.Request(SITE + "/sitemap_index.xml", headers=UA)
    sm = urllib.request.urlopen(r, timeout=60).read().decode("utf-8", "replace")
    print("  sitemap_index.xml:", "ada" if "<sitemapindex" in sm else "TIDAK ADA / bukan sitemap")
    for loc in re.findall(r"<loc>(.*?)</loc>", sm)[:8]:
        print("   ", loc)
except Exception as e:
    print("  sitemap error:", str(e)[:80])
