#!/usr/bin/env python3
"""Cari jejak perubahan massal di TSLaw: kapan artikel diubah, apakah ada skrip/iframe asing di isi."""
import base64, json, re
from collections import Counter
import urllib.error, urllib.request

DOM = "www.tslaw.id"
AUTH = base64.b64encode(b"bambangbot:EFKm EYGx VQCP Y9go ncPr uM2Y").decode()
h = {"Authorization": f"Basic {AUTH}", "User-Agent": "Mozilla/5.0"}


def rest(path):
    try:
        with urllib.request.urlopen(urllib.request.Request(f"https://{DOM}{path}", headers=h), timeout=120) as x:
            return json.loads(x.read())
    except urllib.error.HTTPError as e:
        return {"err": e.code}
    except Exception as e:
        return {"err": str(e)[:50]}


semua = []
for jenis in ("posts", "pages"):
    page = 1
    while True:
        d = rest(f"/wp-json/wp/v2/{jenis}?per_page=100&page={page}&status=publish&context=edit&_fields=id,link,date,modified,content")
        if not isinstance(d, list) or not d:
            break
        semua += [(jenis, x) for x in d]
        if len(d) < 100:
            break
        page += 1

print(f"konten diperiksa: {len(semua)}\n")
print("=== kapan terakhir diubah (10 terbanyak) ===")
per_hari = Counter(x["modified"][:10] for _, x in semua)
for t, n in sorted(per_hari.items(), reverse=True)[:10]:
    print(f"   {t}: {n} konten diubah")

print("\n=== isi yang memuat skrip atau iframe asing ===")
temuan = 0
for jenis, x in semua:
    raw = x["content"]["raw"]
    skrip = re.findall(r"<script[^>]*>", raw, re.I)
    ifr = re.findall(r'<iframe[^>]*src="([^"]+)"', raw, re.I)
    asing = [u for u in ifr if "youtube" not in u.lower() and "google" not in u.lower() and "maps" not in u.lower()]
    if skrip or asing:
        temuan += 1
        print(f"   #{x['id']} {jenis:5} skrip {len(skrip)} · iframe asing {asing[:2]} | {x['link'][:60]}")
print(f"   total: {temuan}")

print("\n=== 5 konten yang paling baru diubah ===")
for jenis, x in sorted(semua, key=lambda y: y[1]["modified"], reverse=True)[:5]:
    print(f"   {x['modified'][:16]} | #{x['id']} {jenis:5} | {x['link'][-58:]}")
