#!/usr/bin/env python3
"""Buat gambar unggulan (Pexels, 1000x567 webp) untuk artikel #10134 lalu pasang sebagai featured image."""
import base64, importlib.util, json, os, re, sys, time, urllib.error, urllib.request

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
sys.path.insert(0, WS)

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"}

PID = 10134
JUDUL = "Dokter Kulit Sidoarjo: Panduan Berobat, Layanan, dan Cara Buat Janji"
OUT = f"{WS}/tsc_feat_dokter-kulit-sidoarjo-panduan-berobat.webp"

import pexels_image as px

print("mencari gambar Pexels...")
ok = px.siapkan_featured(JUDUL, "tsc", OUT, size=(1000, 567))
print(f"hasil: {ok} · berkas ada: {os.path.exists(OUT)}")
if not os.path.exists(OUT):
    sys.exit("gambar tidak terbentuk")

from PIL import Image
im = Image.open(OUT)
print(f"gambar: {im.size} · {os.path.getsize(OUT) // 1024} KB")

# unggah ke pustaka media WordPress
data = open(OUT, "rb").read()
nama = os.path.basename(OUT)
h = {"Authorization": f"Basic {AUTH}", **UA,
     "Content-Type": "image/webp",
     "Content-Disposition": f'attachment; filename="{nama}"'}
r = urllib.request.Request(f"https://{DOM}/wp-json/wp/v2/media", data=data, headers=h, method="POST")
try:
    with urllib.request.urlopen(r, timeout=300) as x:
        med = json.loads(x.read())
    print(f"unggah: HTTP {x.status} · media #{med['id']} · {med.get('source_url')}")
except urllib.error.HTTPError as e:
    sys.exit(f"unggah gagal: HTTP {e.code} {e.read().decode()[:200]}")

# pasang sebagai gambar unggulan
body = json.dumps({"featured_media": med["id"], "alt_text": JUDUL,
                   "caption": "Ilustrasi: konsultasi kulit di klinik"}).encode()
r2 = urllib.request.Request(f"https://{DOM}/wp-json/wp/v2/media/{med['id']}", data=body,
                            headers={"Authorization": f"Basic {AUTH}", "Content-Type": "application/json", **UA},
                            method="POST")
urllib.request.urlopen(r2, timeout=120).read()

body2 = json.dumps({"featured_media": med["id"]}).encode()
r3 = urllib.request.Request(f"https://{DOM}/wp-json/wp/v2/posts/{PID}", data=body2,
                            headers={"Authorization": f"Basic {AUTH}", "Content-Type": "application/json", **UA},
                            method="POST")
with urllib.request.urlopen(r3, timeout=120) as x:
    d3 = json.loads(x.read())
print(f"pasang ke #{PID}: HTTP {x.status} · featured_media = {d3.get('featured_media')} · {d3.get('link')}")

time.sleep(4)
t = urllib.request.urlopen(urllib.request.Request(f"{d3['link']}?cek={int(time.time())}", headers=UA), timeout=90).read().decode("utf-8", "replace")
og = re.search(r'<meta property="og:image" content="([^"]+)"', t)
print(f"og:image di halaman: {og.group(1)[-70:] if og else '(tidak ada)'}")
