#!/usr/bin/env python3
"""TSLaw pra-artikel #15: cek kesehatan situs, zona waktu, status permalink, dan daftar post publish
untuk memilih tautan internal yang benar-benar 200."""
import base64, json, re, 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):
    h = {"Authorization": f"Basic {AUTH}", **UA}
    r = urllib.request.Request(f"https://{DOM}{path}", headers=h)
    for i in range(4):
        try:
            with urllib.request.urlopen(r, timeout=180) as x:
                return x.status, json.loads(x.read())
        except urllib.error.HTTPError as e:
            return e.code, e.read().decode()[:200]
        except Exception as e:
            print(f"    (ulang {i+1}: {str(e)[:70]})")
            time.sleep(8)
    return 0, "gagal"


def get(u, timeout=60):
    try:
        with urllib.request.urlopen(urllib.request.Request(u, headers=UA), timeout=timeout) as x:
            return x.status, x.geturl()
    except urllib.error.HTTPError as e:
        return e.code, e.geturl() if hasattr(e, "geturl") else "-"
    except Exception as e:
        return f"ERR {str(e)[:40]}", "-"


print("=== KESEHATAN ===")
for u in ["https://www.tslaw.id/", "https://tslaw.id/", "https://www.tslaw.id/layanan/",
          "https://www.tslaw.id/hubungi/"]:
    t0 = time.time()
    st, fin = get(u)
    print(f"  {st}  {u}  ({time.time()-t0:.2f}s)")

st, info = rest("/wp-json/")
if isinstance(info, dict):
    print(f"\n  situs: {info.get('name')} | timezone: {info.get('timezone_string')} | permalink: {info.get('home')}")

st, s = rest("/wp-json/wp/v2/settings")
if isinstance(s, dict):
    print(f"  settings url: {s.get('url')} | title: {s.get('title')}")

print("\n=== UJI STRUKTUR ALAMAT ===")
for p in ["/pengacara-terbaik-surabaya/", "/pengacara-terbaik-surabaya.htm",
          "/law-firm-surabaya.htm", "/law-firm-surabaya/",
          "/pengacara-pinjol-ilegal-surabaya.htm", "/konsultan-hukum-perusahaan-surabaya.htm"]:
    st, fin = get("https://www.tslaw.id" + p)
    print(f"  {st}  {p}")

print("\n=== POST PUBLISH (untuk tautan internal) ===")
semua, page = [], 1
while page <= 8:
    st, d = rest(f"/wp-json/wp/v2/posts?status=publish&per_page=100&page={page}"
                 f"&_fields=id,slug,link,title,date")
    if not isinstance(d, list) or not d:
        break
    semua += d
    page += 1
print(f"  total post publish: {len(semua)}")
json.dump(semua, open("/home/mantapman/.hermes/profiles/atun/workspace/drafts/tslaw_posts_publish.json", "w"),
          ensure_ascii=False, indent=1)
print("  disimpan ke drafts/tslaw_posts_publish.json")
print("\n  15 terbaru:")
for p in semua[:15]:
    print(f"    #{p['id']} {p['link']}")
    print(f"        {re.sub('<[^>]+>', '', p['title']['rendered'])}")
