#!/usr/bin/env python3
"""Inventaris lengkap spam judi di klinikmetamorf.com (read-only, belum menghapus apa pun)."""
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()

# kata kunci judi (multi-bahasa: ID, EN, PL, IT, DE, RU, TR)
JUDI = re.compile(
    r"kasyn|kasino|casino|slot|judi|togel|spins|pragmatic|gacor|sportsbook|book of ra|betting|odds|"
    r"bonus senza deposito|wypłacaln|zakład|hazard|glücksspiel|sitzung|1win|1xbet|22bet|betano|mostbet|"
    r"pin-?up|vavada|wincrown|vegastars|bananzia|rtp|jackpot|free spins|no deposit|kasino online",
    re.I)


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=150) 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"}


def kumpul(tipe):
    out, page = [], 1
    while True:
        d = wp(f"/wp-json/wp/v2/{tipe}?per_page=100&page={page}&context=edit"
               f"&_fields=id,title,date,slug,link,author,status,categories")
        if not isinstance(d, list):
            break
        out += d
        if len(d) < 100:
            break
        page += 1
    return out


posts = kumpul("posts")
pages = kumpul("pages")
cats = wp("/wp-json/wp/v2/categories?per_page=100&_fields=id,name,slug,count")
tags = wp("/wp-json/wp/v2/tags?per_page=100&_fields=id,name,slug,count")
users = wp("/wp-json/wp/v2/users?per_page=100&_fields=id,name,slug,roles")

cat_judi = {c["id"]: html.unescape(c["name"]) for c in cats if isinstance(cats, list) and JUDI.search(html.unescape(c["name"]))}
tag_judi = {t["id"]: html.unescape(t["name"]) for t in tags if isinstance(tags, list) and JUDI.search(html.unescape(t["name"]))}

print(f"posts: {len(posts)} | pages: {len(pages)} | kategori: {len(cats) if isinstance(cats,list) else '?'} | tag: {len(tags) if isinstance(tags,list) else '?'}")
print(f"kategori berbau judi: {len(cat_judi)} | tag berbau judi: {len(tag_judi)}")

spam_posts = [p for p in posts if JUDI.search(html.unescape(p["title"]["rendered"]))
              or set(p.get("categories", [])) & set(cat_judi)]
spam_pages = [p for p in pages if JUDI.search(html.unescape(p["title"]["rendered"]))
              or set(p.get("categories", [])) & set(cat_judi)]
bersih = [p for p in posts if p not in spam_posts and p not in spam_pages]

print(f"\nSPAM post : {len(spam_posts)}")
print(f"SPAM page : {len(spam_pages)}")
print(f"konten klinik asli: {len(bersih)}")
if spam_posts:
    tgl = sorted(p["date"][:10] for p in spam_posts)
    print(f"rentang tanggal spam: {tgl[0]} → {tgl[-1]}")
    print("sebaran per hari:", dict(sorted(Counter(p["date"][:10] for p in spam_posts).items())))
    print("author:", dict(Counter(p.get("author") for p in spam_posts)))

print("\n=== kategori judi (untuk dihapus) ===")
for cid, nama in sorted(cat_judi.items(), key=lambda x: x[1])[:25]:
    n = next((c["count"] for c in cats if c["id"] == cid), "?")
    print(f"  #{cid:>5} {nama[:46]:<48} {n} post")
print(f"  ... total {len(cat_judi)} kategori judi")

print("\n=== user yang ada ===")
if isinstance(users, list):
    for u in users:
        print(f"  #{u['id']:>4} {u['name'][:34]:<36} {u.get('roles')} | {u.get('slug','')[:24]}")

print("\n=== contoh 5 konten klinik (memastikan tidak salah hapus) ===")
for p in sorted(bersih, key=lambda x: x["date"], reverse=True)[:5]:
    print(f"  {p['date'][:10]} | #{p['id']} {html.unescape(p['title']['rendered'])[:60]}")

json.dump({"spam_posts": [p["id"] for p in spam_posts], "spam_pages": [p["id"] for p in spam_pages],
           "cat_judi": list(cat_judi.keys()), "tag_judi": list(tag_judi.keys())},
          open("metamorf_spam_inventaris.json", "w"), indent=1)
print("\ninventaris disimpan: metamorf_spam_inventaris.json")
