#!/usr/bin/env python3
"""Diagnosa kenapa meta Yoast TSLaw tidak tersimpan walau HTTP 200."""
import base64, json, time, urllib.request, urllib.error

DOM = "tslaw.id"
AUTH = base64.b64encode(b"bambangbot:EFKm EYGx VQCP Y9go ncPr uM2Y").decode()
UA = {"User-Agent": "Mozilla/5.0"}


def wp(path, method="GET", data=None):
    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 _ in range(3):
        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()[:300]
        except Exception:
            time.sleep(4)
    return 0, "gagal"


st, me = wp("/wp-json/wp/v2/users/me?context=edit")
print("user       :", me.get("name"), "| id", me.get("id"))
print("roles      :", me.get("roles"))
caps = me.get("capabilities") or {}
print("cap penting:", {k: caps.get(k) for k in ("edit_pages", "edit_others_posts", "manage_options", "edit_post_meta")})

st, d = wp("/wp-json/wp/v2/pages/834?context=edit&_fields=id,meta")
print("\nmeta keys pada page 834:", list((d.get("meta") or {}).keys())[:18])

st, w = wp("/wp-json/wp/v2/pages/834", "POST", {"meta": {"_yoast_wpseo_metadesc": "Uji simpan meta TSLaw 25 Sep."}})
print("\nPOST meta  :", st, "(200)" if st == 200 else str(w)[:200])
st, r = wp("/wp-json/wp/v2/pages/834?context=edit&_fields=meta")
print("baca ulang :", repr((r.get("meta") or {}).get("_yoast_wpseo_metadesc")))

st, y = wp("/wp-json/yoast/v1/get_head?url=https://www.tslaw.id/tentang/")
print("\nyoast get_head:", st)
if st == 200 and isinstance(y, dict):
    print("   judul :", (y.get("json") or {}).get("title"))
    print("   desc  :", (y.get("json") or {}).get("description"))
else:
    print("   ", str(y)[:160])

st, ns = wp("/wp-json")
print("\nnamespace REST:", ", ".join(ns.get("namespaces", [])))
