#!/usr/bin/env python3
"""Verifikasi gambar unggulan #10137: tampil di halaman, bisa diakses, dan jadi og:image (meta Yoast)."""
import base64, importlib.util, html, json, re, time, urllib.error, urllib.request

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
spec = importlib.util.spec_from_file_location("cfg", f"{WS}/cfg_tsc.py")
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
CFG = m.CFG
DOM = CFG["domain"]
AUTH = base64.b64encode(f"{CFG['user']}:{CFG['pass']}".encode()).decode()
UA = {"User-Agent": "Mozilla/5.0"}
URL_MEDIA = f"https://www.{DOM}/wp-content/uploads/2026/10/tsc_feat_dokter-kulit-sidoarjo-panduan-berobat.webp"
LINK = f"https://www.{DOM}/dokter-kulit-sidoarjo-panduan-berobat/"

print("=== 1. berkas gambar bisa diakses? ===")
for label, kepala in (("biasa", UA), ("Chrome", {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/124.0",
                                                 "Referer": LINK})):
    try:
        with urllib.request.urlopen(urllib.request.Request(URL_MEDIA, headers=kepala), timeout=45) as x:
            print(f"   {label}: HTTP {x.status} · {len(x.read())//1024} KB · {x.headers.get('content-type')}")
            break
    except urllib.error.HTTPError as e:
        print(f"   {label}: HTTP {e.code}")
    except Exception as e:
        print(f"   {label}: {str(e)[:50]}")

print("\n=== 2. tampil di halaman ===")
t = urllib.request.urlopen(urllib.request.Request(f"{LINK}?cek={int(time.time())}", headers=UA), timeout=90).read().decode("utf-8", "replace")
for pola in (r'<img[^>]+10137[^>]*>', r'src="([^"]*tsc_feat_dokter-kulit-sidoarjo[^"]*)"'):
    m2 = re.findall(pola, t)
    if m2:
        print(f"   {len(m2)} kemunculan: {str(m2[0])[:120]}")
og = re.search(r'<meta property="og:image" content="([^"]+)"', t)
print(f"   og:image sekarang: {og.group(1)[-70:] if og else '-'}")

print("\n=== 3. set og:image Yoast ke gambar unggulan ===")
H = {"Authorization": f"Basic {AUTH}", "Content-Type": "application/json", **UA}
body = json.dumps({"meta": {"_yoast_wpseo_opengraph-image": URL_MEDIA}}).encode()
r = urllib.request.Request(f"https://{DOM}/wp-json/wp/v2/posts/10134", data=body, headers=H, method="POST")
try:
    with urllib.request.urlopen(r, timeout=120) as x:
        d = json.loads(x.read())
    print(f"   HTTP {x.status} · meta opengraph: {str((d.get('meta') or {}).get('_yoast_wpseo_opengraph-image'))[-60:]}")
except urllib.error.HTTPError as e:
    print(f"   gagal: HTTP {e.code} {e.read().decode()[:120]}")

time.sleep(5)
t2 = urllib.request.urlopen(urllib.request.Request(f"{LINK}?cek={int(time.time())}", headers=UA), timeout=90).read().decode("utf-8", "replace")
og2 = re.search(r'<meta property="og:image" content="([^"]+)"', t2)
print(f"   og:image sesudah: {og2.group(1)[-70:] if og2 else '-'}")
