#!/usr/bin/env python3
"""DAS: verifikasi akhir perbaikan gambar artikel + ukur dampaknya terhadap permintaan gambar."""
import base64, json, re, time, urllib.request, importlib.util

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
spec = importlib.util.spec_from_file_location("cfg_das", f"{WS}/cfg_das.py")
m = importlib.util.module_from_spec(spec); spec.loader.exec_module(m)
CFG = m.CFG
DOM, AUTH = CFG["domain"], base64.b64encode(f'{CFG["user"]}:{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(4):
        try:
            with urllib.request.urlopen(r, timeout=220) as x:
                return json.loads(x.read())
        except Exception:
            time.sleep(6)
    return []


posts, page = [], 1
while True:
    d = rest(f"/wp-json/wp/v2/posts?per_page=100&page={page}&status=publish&context=edit&_fields=id,slug,content")
    if not isinstance(d, list):
        break
    posts += d
    if len(d) < 100:
        break
    page += 1

total = srcset = lazy = dim = decoding = 0
artikel_ok = []
for p in posts:
    raw = p.get("content", {}).get("raw", "") or ""
    tags = re.findall(r"<img[^>]*>", raw, re.I)
    total += len(tags)
    s = sum(1 for t in tags if "srcset=" in t)
    l = sum(1 for t in tags if "loading=" in t)
    dm = sum(1 for t in tags if 'width="' in t and 'height="' in t)
    dc = sum(1 for t in tags if "decoding=" in t)
    srcset += s; lazy += l; dim += dm; decoding += dc
    if tags and s == len(tags) and l == len(tags):
        artikel_ok.append(p["id"])

print(f"artikel: {len(posts)} | gambar di isi: {total}")
print(f"   sudah punya srcset   : {srcset}")
print(f"   sudah punya loading  : {lazy}")
print(f"   sudah punya dimensi  : {dim}")
print(f"   sudah punya decoding : {decoding}")
print(f"   artikel yang seluruh gambarnya beres: {len(artikel_ok)}")

print("\n=== uji nyata: berapa gambar yang diunduh ponsel pada satu artikel ===")
u = "/bengkel-spesialis-pajero-di-surabaya/"
try:
    h = urllib.request.urlopen(urllib.request.Request(f"https://dasindonesia.com{u}", headers=UA), timeout=150).read().decode("utf-8", "replace")
    ss = re.findall(r'srcset="([^"]+)"', h)
    print(f"   {u} → {len(ss)} elemen srcset di halaman")
    if ss:
        print("   contoh srcset:", ss[0][:220])
    print("   atribut lazy di halaman:", len(re.findall(r'loading="lazy"', h)), "| data-lazy-src (Rocket):", len(re.findall(r"data-lazy-src=", h)))
except Exception as e:
    print("   gagal:", str(e)[:80])
