#!/usr/bin/env python3
"""TSLaw: periksa sebelum membereskan — halaman sampah, jadwal artikel, zona waktu, penanda WP Rocket."""
import base64, html, json, re, time, urllib.request, urllib.error

DOM = "tslaw.id"
AUTH = base64.b64encode(b"bambangbot:EFKm EYGx VQCP Y9go ncPr uM2Y").decode()
UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/124 Safari/537.36"}


def wp(path, method="GET", data=None):
    h = {"Authorization": f"Basic {AUTH}", **UA}
    body = None
    if data is not None:
        body = json.dumps(data).encode(); h["Content-Type"] = "application/json"
    r = urllib.request.Request(f"https://{DOM}{path}", data=body, headers=h, method=method)
    for _ in range(3):
        try:
            with urllib.request.urlopen(r, timeout=120) as x:
                return x.status, json.loads(x.read())
        except urllib.error.HTTPError as e:
            return e.code, e.read().decode()[:250]
        except Exception:
            time.sleep(4)
    return 0, "gagal"


print("=== 1. kandidat sampah: halaman & artikel bawaan ===")
for tipe in ("pages", "posts"):
    st, d = wp(f"/wp-json/wp/v2/{tipe}?per_page=100&status=publish,draft,trash&_fields=id,title,slug,status,link")
    if not isinstance(d, list):
        print(f"  {tipe}: {st} {d}"); continue
    for p in d:
        judul = html.unescape(p["title"]["rendered"])
        if re.search(r"sample page|hello world|contoh halaman|halo dunia", judul, re.I) or \
           re.search(r"sample-page|hello-world", p["slug"], re.I):
            print(f"  {tipe[:-1]:<6} #{p['id']:>5} [{p['status']:<7}] {judul[:40]:<42} {p['link']}")

print("\n=== 2. artikel terjadwal (penting sebelum ubah zona waktu) ===")
st, d = wp("/wp-json/wp/v2/posts?per_page=30&status=future&orderby=date&order=asc&_fields=id,title,date")
print(f"  HTTP {st} | jumlah: {len(d) if isinstance(d, list) else '?'}")
if isinstance(d, list):
    for p in d:
        print(f"   #{p['id']} {p['date']} {html.unescape(p['title']['rendered'])[:50]}")

print("\n=== 3. pengaturan situs sekarang ===")
st, s = wp("/wp-json/wp/v2/settings")
if isinstance(s, dict):
    for k in ("title", "description", "timezone", "url", "email", "posts_per_page", "default_ping_status"):
        if k in s:
            print(f"   {k:<20}: {str(s[k])[:70]}")
    print(f"   (kunci lain yang tersedia: {len(s)})")
else:
    print("  ", st, s)

print("\n=== 4. penanda cache di HTML beranda ===")
h = urllib.request.urlopen(urllib.request.Request(f"https://www.{DOM}/", headers=UA), timeout=90)
isi = h.read().decode("utf-8", "replace")
for k in ("cf-cache-status", "x-cache", "x-powered-by", "cache-control", "expires", "server"):
    print(f"   {k:<18}: {h.headers.get(k)}")
print("   jejak WP Rocket di HTML :", "ADA" if "WP Rocket" in isi or "wp-rocket" in isi else "tidak ada")
print("   jumlah <script>         :", len(re.findall(r"<script", isi)))
print("   jumlah file CSS         :", len(re.findall(r'rel=["\']stylesheet', isi)))
print("   gambar tanpa loading=lazy:", len([m for m in re.findall(r"<img[^>]+>", isi) if "loading=" not in m]))
print("   total <img>             :", len(re.findall(r"<img", isi)))
