#!/usr/bin/env python3
"""DAS: verifikasi akhir konsolidasi klaster di halaman LIVE (pakai URL asli dari API)."""
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 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/124 Safari/537.36"}

KLASTER = {"Alphard": (5569, [6304, 6566]), "Nissan": (5657, [8081]), "Lexus": (5684, [6708, 6705]),
           "Innova": (6392, [6932, 5600]), "Pajero": (6430, [6435, 5603]), "Mercy": (8296, [6711])}


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=150) as x:
                return json.loads(x.read())
        except Exception:
            time.sleep(4)
    return {}


def live(u):
    try:
        r = urllib.request.urlopen(urllib.request.Request(f"{u}?v={int(time.time())}", headers=UA), timeout=120)
        return r.status, r.read().decode("utf-8", "replace")
    except Exception as e:
        return 0, str(e)[:60]


print("=== HALAMAN PEMENANG (harus index, isi bertambah) ===")
for nama, (mid, kalah) in KLASTER.items():
    p = rest(f"/wp-json/wp/v2/posts/{mid}?context=edit&_fields=link,title")
    st, h = live(p["link"])
    rob = re.findall(r"<meta name=.robots. content=.([^\"']+)", h)
    kata = len(re.sub(r"<[^>]+>", " ", re.sub(r"<script.*?</script>|<style.*?</style>", " ", h, flags=re.S)).split())
    print(f"   {nama:<8} #{mid} status {st} | {rob[0][:12] if rob else '-'} | ±{kata} kata halaman | tombol {len(re.findall('AMBIL PROMO', h, re.I))}x")

print("\n=== ARTIKEL YANG DIKONSOLIDASI (harus noindex) ===")
for nama, (mid, kalah) in KLASTER.items():
    for pid in kalah:
        p = rest(f"/wp-json/wp/v2/posts/{pid}?context=edit&_fields=link")
        st, h = live(p["link"])
        rob = re.findall(r"<meta name=.robots. content=.([^\"']+)", h)
        ok = bool(rob) and "noindex" in rob[0]
        print(f"   {'✅' if ok else '❌'} {nama:<8} #{pid} status {st} | {rob[0][:14] if rob else 'tanpa robots'} | {p['link'].replace('https://dasindonesia.com', '')[:52]}")
