#!/usr/bin/env python3
"""TSLaw: periksa cache sisi situs (WP Rocket) + ukur waktu tanggap berulang + siapkan temuan untuk cache Cloudflare."""
import re, time, urllib.request, urllib.error

UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/124.0 Safari/537.36"}
DOM = "https://www.tslaw.id"


def ambil(u, timeout=120):
    t0 = time.time()
    try:
        with urllib.request.urlopen(urllib.request.Request(u, headers=UA), timeout=timeout) as x:
            isi = x.read()
            return x.status, isi.decode("utf-8", "replace"), time.time() - t0, dict(x.headers)
    except Exception as e:
        return 0, "", time.time() - t0, {"err": str(e)[:80]}


print("=== 5 kali berturut-turut (beranda) ===")
for i in range(5):
    st, h, d, head = ambil(f"{DOM}/?v={int(time.time())}{i}")
    tanda_cache = [k for k in head if k.lower() in ("x-cache", "x-cache-status", "cf-cache-status", "cache-control",
                                                    "age", "x-rocket-nginx", "x-powered-by")]
    print(f"   {i+1}. status {st} | {d:5.2f}s | {len(h):>7} byte | {[(k, head[k][:30]) for k in tanda_cache]}")
    time.sleep(1)

print("\n=== tanda cache WP Rocket di HTML ===")
st, h, d, _ = ambil(DOM + "/")
print("   komentar 'Performance optimized by WP Rocket':", "Performance optimized by WP Rocket" in h)
print("   jejak cache lain:", re.findall(r"<!--[^>]{0,80}(?:rocket|cache)[^>]{0,80}-->", h, re.I)[:3])
print("   kelas wpr-*:", len(re.findall(r"wpr-", h)))
print("   versi tema/plugin menandakan halaman dinamis:", sorted(set(re.findall(r"wp-content/plugins/([a-z0-9\-_]+)", h)))[:10])

print("\n=== halaman dalam (artikel) 3 kali ===")
u = "/6-langkah-mengurus-sengketa-tanah-secara-hukum-di-indonesia/"
for i in range(3):
    st, h, d, head = ambil(f"{DOM}{u}?v={int(time.time())}{i}")
    print(f"   {i+1}. status {st} | {d:5.2f}s | {len(h):>7} byte | cf: {head.get('cf-cache-status')}")

print("\n=== apakah HTML berubah antar permintaan (aman untuk di-cache?) ===")
st1, h1, _, _ = ambil(DOM + "/?a=1")
st2, h2, _, _ = ambil(DOM + "/?b=2")
import difflib
beda = sum(1 for _ in difflib.unified_diff(h1.split("\n"), h2.split("\n"), n=0))
print(f"   panjang: {len(h1)} vs {len(h2)} | baris berbeda (perkiraan): {beda}")
print("   ada cookie sesi pengguna di HTML:", bool(re.search(r"wordpress_logged_in|wp-settings-", h1)))
print("   ada keranjang/checkout (bahaya bila di-cache):", bool(re.search(r"woocommerce|add-to-cart", h1, re.I)))
