#!/usr/bin/env python3
"""DMark: verifikasi apakah perubahan judul benar-benar diterapkan di render server."""
import base64, json, re, time, urllib.request, importlib.util

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
spec = importlib.util.spec_from_file_location("cfg_dmark", f"{WS}/cfg_dmark.py")
m = importlib.util.module_from_spec(spec); spec.loader.exec_module(m)
DOM = m.CFG.get("domain", "www.dmark.id")
AUTH = base64.b64encode(f'{m.CFG["user"]}:{m.CFG["pass"]}'.encode()).decode()
UA = {"User-Agent": "Mozilla/5.0"}


def rest(p):
    r = urllib.request.Request(f"https://{DOM}{p}", headers={"Authorization": f"Basic {AUTH}", **UA})
    for _ in range(3):
        try:
            with urllib.request.urlopen(r, timeout=180) as x:
                return json.loads(x.read())
        except Exception:
            time.sleep(4)
    return []


print("=== render server (REST content.rendered) ===")
d = rest("/wp-json/wp/v2/pages/2034?context=view&_fields=content")
rendah = d["content"]["rendered"]
pos = rendah.find("Creativity is Intelegence")
tag = re.findall(r"<h([1-6])[^>]*>[^<]*Creativity is Intelegence", rendah)
print(f"   tag judul kutipan di render server: {['h'+t for t in tag] or '?'}")
print(f"   cuplikan: {re.sub(chr(10), ' ', rendah[max(0,pos-200):pos+40])[-240:]}")

print("\n=== jumlah tag judul di render server ===")
from collections import Counter
print("   ", Counter(re.findall(r"<h([1-6])[^>]*>", rendah)))

print("\n=== halaman kanonik /home-2/ (live) ===")
import urllib.request as u2
for u in ("https://www.dmark.id/home-2/", "https://www.dmark.id/?p=2034"):
    h = u2.urlopen(u2.Request(u, headers=UA), timeout=90).read().decode("utf-8", "replace")
    tag = re.findall(r"<h([1-6])[^>]*>[^<]*Creativity is Intelegence", h)
    print(f"   {u:<40} tag: {['h'+t for t in tag] or '?'} | panjang {len(h):,}")
