#!/usr/bin/env python3
"""TSLaw: baca meta Yoast halaman /tentang/ dan halaman lain (judul, deskripsi, fokus) + yang tampil di live."""
import base64, html, json, re, time, urllib.request, urllib.error, importlib.util

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
spec = importlib.util.spec_from_file_location("cfg_tslaw", f"{WS}/cfg_tslaw.py")
m = importlib.util.module_from_spec(spec); spec.loader.exec_module(m)
CFG = m.CFG
DOM, AUTH = CFG["domain"] if "domain" in CFG else ("www.tslaw.id", None), None
DOM = "www.tslaw.id"
UA = {"User-Agent": "Mozilla/5.0"}

USER, PASS = CFG.get("user"), CFG.get("pass")
AUTH = base64.b64encode(f"{USER}:{PASS}".encode()).decode()


def rest(p):
    r = urllib.request.Request(f"https://{DOM}{p}", headers={"Authorization": f"Basic {AUTH}", **UA})
    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()[:200]
    except Exception as e:
        return 0, str(e)[:120]


print("=== halaman (page) di TSLaw ===")
st, d = rest("/wp-json/wp/v2/pages?per_page=50&context=edit&_fields=id,slug,link,title,meta")
if isinstance(d, list):
    for p in d:
        print(f"   #{p['id']:>4} /{p['slug']:<22} {html.unescape(re.sub('<[^>]+>','',p['title']['raw']))[:44]}")
        print(f"        meta via REST: {json.dumps(p.get('meta'))[:160]}")
else:
    print("   gagal:", str(d)[:150])

print("\n=== yang tampil di halaman live ===")
for u in ("/tentang/", "/layanan/", "/"):
    try:
        h = urllib.request.urlopen(urllib.request.Request(f"https://{DOM}{u}", headers=UA), timeout=90).read().decode("utf-8", "replace")
        t = re.search(r"<title[^>]*>(.*?)</title>", h, re.S)
        de = re.search(r'<meta name="description" content="([^"]*)"', h)
        og = re.search(r'<meta property="og:title" content="([^"]*)"', h)
        can = re.findall(r'<link rel="canonical" href="([^"]+)"', h)
        h1 = re.findall(r"<h1[^>]*>(.*?)</h1>", h, re.S)
        print(f"\n   {u}")
        print(f"      <title>     : {html.unescape(t.group(1)).strip()[:110] if t else '-'}")
        print(f"      description : {html.unescape(de.group(1))[:150] if de else '(tidak ada)'} "
              f"{'(' + str(len(html.unescape(de.group(1)))) + ' char)' if de else ''}")
        print(f"      og:title    : {html.unescape(og.group(1))[:90] if og else '-'}")
        print(f"      canonical   : {can}")
        print(f"      H1          : {[html.unescape(re.sub('<[^>]+>','',x)).strip()[:70] for x in h1[:2]]}")
    except Exception as e:
        print(f"   {u}: gagal {str(e)[:70]}")
