#!/usr/bin/env python3
"""DAS: periksa penyebab jatuh 21–22 Agu — suntikan spam, artikel baru mencurigakan, dan kondisi situs."""
import base64, json, re, time, urllib.request, urllib.error, importlib.util
from collections import Counter

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
spec = importlib.util.spec_from_file_location("cfg_das", f"{WS}/cfg_das.py")
m = importlib.util.module_from_spec(spec); spec.loader.exec_module(m)
CFG = m.CFG
DOM, AUTH = CFG["domain"], base64.b64encode(f'{CFG["user"]}:{CFG["pass"]}'.encode()).decode()
UA = {"User-Agent": "Mozilla/5.0"}

SPAM = ["slot", "gacor", "togel", "judi", "sbobet", "casino", "bandar", "maxwin", "rtp",
        "poker", "toto", "betting", "viagra", "payday loan", "forex", "crypto pump"]


def rest(p):
    r = urllib.request.Request(f"https://{DOM}{p}", headers={"Authorization": f"Basic {AUTH}", **UA})
    for _ in range(3):
        try:
            with urllib.request.urlopen(r, timeout=180) as x:
                return json.loads(x.read())
        except Exception:
            time.sleep(4)
    return []


print("=== 1. artikel & halaman: kapan dibuat/diubah ===")
post, page = [], 1
while True:
    d = rest(f"/wp-json/wp/v2/posts?per_page=100&page={page}&status=publish&context=edit&_fields=id,slug,title,content,date,modified,author")
    if not isinstance(d, list):
        break
    post += d
    if len(d) < 100:
        break
    page += 1
hal = rest("/wp-json/wp/v2/pages?per_page=100&status=publish&context=edit&_fields=id,slug,title,content,date,modified,author")
print(f"   artikel: {len(post)} | halaman: {len(hal) if isinstance(hal, list) else '?'}")

print("\n   artikel yang dibuat/diubah 15 Agu – 1 Sep 2026:")
for p in sorted(post, key=lambda x: x["modified"]):
    if "2026-08-15" <= p["modified"][:10] <= "2026-09-01" or "2026-08-15" <= p["date"][:10] <= "2026-09-01":
        print(f"      #{p['id']:>5} dibuat {p['date'][:10]} · diubah {p['modified'][:10]} · penulis {p['author']} | "
              f"{re.sub('<[^>]+>', '', p['title']['raw'])[:52]}")
if isinstance(hal, list):
    for p in hal:
        if "2026-08-01" <= p["modified"][:10] <= "2026-09-05":
            print(f"      HALAMAN #{p['id']} diubah {p['modified'][:10]} | {re.sub('<[^>]+>', '', p['title']['raw'])[:52]}")

print("\n=== 2. sisir kata kunci spam di seluruh isi ===")
temuan = Counter()
contoh = {}
for p in (post + (hal if isinstance(hal, list) else [])):
    teks = (p["content"]["raw"] or "").lower()
    for k in SPAM:
        n = teks.count(k)
        if n:
            temuan[k] += n
            contoh.setdefault(k, []).append((p["id"], re.sub("<[^>]+>", "", p["title"]["raw"])[:44]))
if temuan:
    for k, n in temuan.most_common():
        print(f"   {k:<14} {n:>3}x | contoh: {contoh[k][:2]}")
else:
    print("   ✅ tidak ada kata kunci spam di konten")

print("\n=== 3. tautan keluar mencurigakan di konten (tanda suntikan) ===")
luar = Counter()
for p in post:
    for u in re.findall(r'href="(https?://[^"]+)"', p["content"]["raw"] or ""):
        d = re.sub(r"^https?://(www\.)?", "", u).split("/")[0].lower()
        if "dasindonesia" in d or "wa.me" in d or "whatsapp" in d or "linktr" in d:
            continue
        luar[d] += 1
for d, n in luar.most_common(12):
    print(f"   {n:>3}x {d}")

print("\n=== 4. kondisi situs saat ini (beranda & beberapa URL) ===")
import urllib.request as u2
for u in ("/", "/robots.txt", "/sitemap_index.xml", "/wp-login.php"):
    try:
        r = u2.urlopen(u2.Request(f"https://{DOM}{u}", headers=UA), timeout=60)
        print(f"   {r.status} | {len(r.read()):>7} byte | {u}")
    except Exception as e:
        print(f"   GAGAL {str(e)[:50]} | {u}")
