#!/usr/bin/env python3
"""Ganti gambar unggulan artikel TSLaw #3566 dengan foto Pexels yang diminta Bos."""
import base64, importlib.util, json, os, re, time, urllib.error, urllib.request

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
spec = importlib.util.spec_from_file_location("cfg", f"{WS}/cfg_tslaw.py")
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
CFG = m.CFG
DOM = CFG.get("domain", CFG.get("situs"))
PID = 3566
BERKAS = "/tmp/pexels_8112198.jpg"
SUMBER = "https://images.pexels.com/photos/8112198/pexels-photo-8112198.jpeg"

A = base64.b64encode(f"{CFG['user']}:{CFG['pass']}".encode()).decode()
UA = {"User-Agent": "Mozilla/5.0"}
H = {"Authorization": f"Basic {A}", **UA}
HJ = {**H, "Content-Type": "application/json"}


def rest(p, method="GET", data=None, kepala=None):
    h = dict(kepala or HJ)
    body = json.dumps(data).encode() if data is not None else None
    r = urllib.request.Request(f"https://{DOM}{p}", data=body, headers=h, method=method)
    with urllib.request.urlopen(r, timeout=300) as x:
        return x.status, json.loads(x.read())


st, post = rest(f"/wp-json/wp/v2/posts/{PID}?context=edit&_fields=id,title,link,featured_media")
print(f"artikel #{PID}: {re.sub('<[^>]+>', '', post['title']['raw'])}")
print(f"   {post['link']}")
print(f"   gambar unggulan sekarang: {post.get('featured_media') or 'TIDAK ADA'}")

data = open(BERKAS, "rb").read()
nama = "tslaw-law-firm-surabaya-kantor.jpg"
hh = {**H, "Content-Type": "image/jpeg", "Content-Disposition": f'attachment; filename="{nama}"'}
r = urllib.request.Request(f"https://{DOM}/wp-json/wp/v2/media", data=data, headers=hh, 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['source_url']}")
except urllib.error.HTTPError as e:
    raise SystemExit(f"unggah gagal: HTTP {e.code} {e.read().decode()[:200]}")

st2, _ = rest(f"/wp-json/wp/v2/media/{med['id']}", "POST",
              {"alt_text": "Kantor law firm di Surabaya dengan meja kerja dan dokumen perkara",
               "title": "Gambar unggulan: Biaya Jasa Law Firm Surabaya",
               "caption": f"Foto: Pexels ({SUMBER})"})
st3, d3 = rest(f"/wp-json/wp/v2/posts/{PID}", "POST", {"featured_media": med["id"]})
print(f"pasang: HTTP {st3} · featured_media = {d3.get('featured_media')}")

time.sleep(5)
st4, cek = rest(f"/wp-json/wp/v2/posts/{PID}?context=edit&_fields=featured_media")
print(f"baca balik: featured_media = {cek.get('featured_media')}")

t = urllib.request.urlopen(urllib.request.Request(f"{post['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) if og else '(tidak ada)'}")
