#!/usr/bin/env python3
"""Cek TSLaw sebelum menulis artikel ke-14 (pengacara terbaik Surabaya):
kesehatan situs, daftar post (id, slug, judul, status) untuk cek kanibalisasi + tautan internal.
"""
import base64, json, re, sys, 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 rest(path, method="GET", data=None, tries=4):
    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 i in range(tries):
        try:
            with urllib.request.urlopen(r, timeout=120) as x:
                return x.status, json.loads(x.read()), dict(x.headers)
        except urllib.error.HTTPError as e:
            return e.code, e.read().decode()[:200], {}
        except Exception as e:
            print(f"   (ulang {i+1}: {str(e)[:60]})")
            time.sleep(6)
    return 0, "gagal", {}


print("=== KESEHATAN SITUS ===")
for u in ("https://www.tslaw.id/", "https://tslaw.id/", "https://www.tslaw.id/layanan/",
          "https://www.tslaw.id/pengacara-terbaik-surabaya/"):
    try:
        req = urllib.request.Request(u, headers=UA)
        t0 = time.time()
        with urllib.request.urlopen(req, timeout=60) as x:
            print(f"  {x.status}  {u}  {time.time()-t0:.2f}s")
    except urllib.error.HTTPError as e:
        print(f"  {e.code}  {u}")
    except Exception as e:
        print(f"  ERR {str(e)[:50]}  {u}")

st, info, _ = rest("/wp-json/")
print(f"\n  API: {st} | zona waktu: {info.get('timezone_string') if isinstance(info, dict) else info}")

print("\n=== POST (semua status) ===")
posts = []
page = 1
while page <= 6:
    st, data, hd = rest(f"/wp-json/wp/v2/posts?per_page=100&page={page}&status=any"
                        f"&_fields=id,slug,title,status,date,link&orderby=date&order=desc")
    if not isinstance(data, list) or not data:
        break
    posts += data
    total = hd.get("X-WP-Total", "?")
    if len(data) < 100:
        break
    page += 1
print(f"  {len(posts)} post (X-WP-Total={total} halaman terakhir)")
for p in posts[:25]:
    print(f"   #{p['id']:>5} {p['status']:<8} {p['date'][:10]} /{p['slug']}/")

kunci = ("pengacara", "advokat", "law-firm", "law firm", "bantuan hukum", "notaris", "mediator",
         "pajak", "kecelakaan", "perdata", "pidana", "pinjol", "pinjaman")
print("\n=== KANDIDAT KANIBALISASI / TAUTAN INTERNAL ===")
for p in posts:
    teks = (p["title"]["rendered"] + " " + p["slug"]).lower()
    if any(k in teks for k in kunci):
        print(f"   #{p['id']:>5} {p['status']:<8} {p['title']['rendered'][:85]}")
        print(f"          https://www.tslaw.id/{p['slug']}/")

json.dump(posts, open("/home/mantapman/.hermes/profiles/atun/workspace/tslaw_listikel/_post14.json", "w"),
          ensure_ascii=False, indent=1)
print("\n  daftar disimpan: tslaw_listikel/_post14.json")
