#!/usr/bin/env python3
"""Diagnosa: apakah og:image LEIT 4147 mengikuti featured image? (uji pakai media 4182 lalu balik 4216)"""
import base64, json, urllib.request, urllib.error, time

SITE = "https://www.leitsurabaya.com"
AUTH = base64.b64encode(b"bambangbot:zibd dLIV xY8x onP9 39qL hiNr").decode()


def req(method, path, data=None):
    h = {"Authorization": f"Basic {AUTH}", "User-Agent": "Mozilla/5.0"}
    body = None
    if data is not None:
        body = json.dumps(data).encode()
        h["Content-Type"] = "application/json"
    r = urllib.request.Request(SITE + path, data=body, headers=h, method=method)
    try:
        with urllib.request.urlopen(r, timeout=120) as resp:
            return resp.status, json.loads(resp.read())
    except urllib.error.HTTPError as e:
        return e.code, e.read().decode()[:300]


def og():
    st, j = req("GET", "/wp-json/wp/v2/posts/4147?context=edit&_fields=featured_media,yoast_head_json")
    i = j["yoast_head_json"].get("og_image")
    return j["featured_media"], (i[0]["url"].split("/")[-1] if i else None)


print("sebelum      :", og())
print("set 4182 ->", req("POST", "/wp-json/wp/v2/posts/4147", {"featured_media": 4182})[0])
time.sleep(3)
print("sesudah 4182 :", og())
print("balik 4216 ->", req("POST", "/wp-json/wp/v2/posts/4147", {"featured_media": 4216})[0])
time.sleep(3)
print("final        :", og())
