#!/usr/bin/env python3
"""Unggah gambar unggulan hasil desain ke pustaka media TSC, lalu pasang ke artikel #10134."""
import base64, importlib.util, json, os, re, sys, 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"}

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

data = open(BERKAS, "rb").read()
nama = os.path.basename(BERKAS)
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]}")

H = {"Authorization": f"Basic {AUTH}", "Content-Type": "application/json", **UA}
r2 = urllib.request.Request(f"https://{DOM}/wp-json/wp/v2/media/{med['id']}",
                            data=json.dumps({"alt_text": JUDUL, "title": "Gambar unggulan: Dokter Kulit Sidoarjo"}).encode(),
                            headers=H, method="POST")
urllib.request.urlopen(r2, timeout=120).read()

r3 = urllib.request.Request(f"https://{DOM}/wp-json/wp/v2/posts/{PID}",
                            data=json.dumps({"featured_media": med["id"]}).encode(), headers=H, 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')}")
print(f"halaman: {d3.get('link')}")

time.sleep(6)
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)
img = re.findall(r'<img[^>]+wp-post-image[^>]+>', t)
print(f"og:image: {og.group(1)[-72:] if og else '(tidak ada)'}")
print(f"tag gambar unggulan di halaman: {'ada' if img else 'belum tampak (mungkin cache)'}")
