#!/usr/bin/env python3
"""Pemeriksaan TSLaw (tslaw.id): HTTP & redirect, HTTPS, WordPress, konten, plugin, sitemap."""
import base64, html, json, ssl, socket, time, urllib.request, urllib.error

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


def cek_url(u, redirect=True):
    class NoRedir(urllib.request.HTTPRedirectHandler):
        def redirect_request(self, *a, **k):
            return None if not redirect else super().redirect_request(*a, **k)
    op = urllib.request.build_opener(NoRedir)
    t0 = time.time()
    try:
        r = op.open(urllib.request.Request(u, headers=UA), timeout=45)
        return {"kode": r.status, "detik": round(time.time() - t0, 2), "lokasi": r.headers.get("Location"),
                "server": r.headers.get("Server"), "cf": r.headers.get("cf-cache-status"),
                "ukuran": len(r.read())}
    except urllib.error.HTTPError as e:
        return {"kode": e.code, "detik": round(time.time() - t0, 2), "lokasi": e.headers.get("Location"),
                "server": e.headers.get("Server"), "cf": e.headers.get("cf-cache-status"), "ukuran": 0}
    except Exception as e:
        return {"kode": 0, "error": str(e)[:80], "detik": round(time.time() - t0, 2)}


print("=== 1. HTTP & redirect ===")
for u in (f"http://{DOM}/", f"https://{DOM}/", f"https://www.{DOM}/", f"https://{DOM}/robots.txt",
          f"https://{DOM}/sitemap_index.xml"):
    d = cek_url(u, redirect=False)
    print(f"  {u:<40} → {d.get('kode')} | {d.get('detik')}s | Location: {str(d.get('lokasi'))[:52]} | "
          f"server={d.get('server')} cf={d.get('cf')} | {d.get('ukuran')}b")

print("\n=== 2. HTTPS / sertifikat ===")
try:
    ctx = ssl.create_default_context()
    with socket.create_connection((DOM, 443), timeout=20) as s:
        with ctx.wrap_socket(s, server_hostname=DOM) as ss:
            c = ss.getpeercert()
    print("   penerbit :", dict(x[0] for x in c["issuer"]).get("organizationName"))
    print("   berlaku  :", c["notBefore"], "→", c["notAfter"])
except Exception as e:
    print("   gagal:", str(e)[:100])


def wp(path):
    r = urllib.request.Request(f"https://{DOM}{path}", headers={"Authorization": f"Basic {AUTH}", **UA})
    for _ in range(3):
        try:
            with urllib.request.urlopen(r, timeout=120) as x:
                return json.loads(x.read()), dict(x.headers), x.status
        except urllib.error.HTTPError as e:
            return {"__err": e.code}, {}, e.code
        except Exception:
            time.sleep(4)
    return {"__err": "gagal"}, {}, 0


print("\n=== 3. WordPress ===")
root, _, _ = wp("/wp-json")
print("   nama situs :", root.get("name"))
print("   deskripsi  :", root.get("description"))
print("   zona waktu :", root.get("timezone_string"), "| offset", root.get("gmt_offset"))

d, h, st = wp("/wp-json/wp/v2/posts?per_page=5&status=publish&_fields=id,title,date,link")
print(f"\n=== 4. Artikel terakhir (HTTP {st}) ===")
if isinstance(d, list):
    for p in d:
        print(f"   #{p['id']:>5} {p['date'][:10]} {html.unescape(p['title']['rendered'])[:56]}")
        print(f"          {p['link']}")
for status in ("publish", "future", "draft"):
    _, hh, _ = wp(f"/wp-json/wp/v2/posts?per_page=1&status={status}&_fields=id")
    print(f"   total {status:<8}: {hh.get('X-WP-Total', '?')}")

pl, _, _ = wp("/wp-json/wp/v2/plugins?_fields=plugin,name,status,version")
print("\n=== 5. Plugin ===")
if isinstance(pl, list):
    for p in sorted(pl, key=lambda x: x.get("status", "")):
        print(f"   [{p.get('status','?'):<9}] {p.get('name','?')[:40]:<42} v{str(p.get('version'))[:10]:<10} {p['plugin']}")

print("\n=== 6. SEO: Yoast, sitemap, judul halaman depan ===")
pg, _, _ = wp("/wp-json/wp/v2/pages?per_page=100&_fields=id,link,title")
print(f"   halaman tetap: {len(pg) if isinstance(pg, list) else '?'}")
if isinstance(pg, list):
    for p in pg[:12]:
        print(f"     #{p['id']:>5} {p['link'].replace('https://tslaw.id', '')[:52]:<54} {html.unescape(p['title']['rendered'])[:34]}")
