#!/usr/bin/env python3
"""Terbitkan draf #10134 lalu verifikasi di halaman live."""
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"}
PID = 10134


def kirim(path, method="GET", data=None):
    h = {"Authorization": f"Basic {AUTH}", **UA}
    body = None
    if data is not None:
        body = json.dumps(data).encode()
        h["Content-Type"] = "application/json"
    r = urllib.request.Request(f"https://{DOM}{path}", data=body, headers=h, method=method)
    for _ in range(3):
        try:
            with urllib.request.urlopen(r, timeout=180) as x:
                return x.status, json.loads(x.read())
        except urllib.error.HTTPError as e:
            return e.code, e.read().decode()[:200]
        except Exception:
            time.sleep(4)
    return 0, "gagal"


st, d = kirim(f"/wp-json/wp/v2/posts/{PID}", "POST", {"status": "publish"})
print(f"terbitkan: HTTP {st} · status {d.get('status') if isinstance(d, dict) else d}")
link = d.get("link") if isinstance(d, dict) else None
time.sleep(3)

# minta WP Rocket membuat ulang CSS terpakai untuk halaman ini
st2, d2 = kirim(f"/wp-rocket/v1/cpcss/post/{PID}", "POST", {})
print(f"rebuild CSS terpakai: HTTP {st2}")

time.sleep(8)
try:
    t = urllib.request.urlopen(urllib.request.Request(f"{link}?cek={int(time.time())}", headers=UA), timeout=90).read().decode("utf-8", "replace")
    jl = re.search(r"<title>(.*?)</title>", t, re.S)
    dl = re.search(r'<meta name="description" content="([^"]*)"', t)
    print(f"\nhalaman live: {link}")
    print(f"   HTTP 200 · panjang {len(t)} char")
    print(f"   judul : {html.unescape(jl.group(1)).strip()[:90] if jl else '-'}")
    print(f"   deskripsi: {html.unescape(dl.group(1)).strip()[:100] if dl else '-'}")
    print(f"   tombol WA: {'ada' if 'wa.me/6285117444417' in t else 'TIDAK ADA'}")
    dalam = re.findall(r'href="(https://www\.theskincodeclinic\.com/[^"]+)"', t)
    print(f"   tautan internal: {len(set(dalam))}")
    print(f"   H2 di halaman: {t.count('<h2')}")
except urllib.error.HTTPError as e:
    print(f"   ❌ halaman live HTTP {e.code}")
except Exception as e:
    print(f"   ❌ gagal membaca halaman: {str(e)[:80]}")
