#!/usr/bin/env python3
"""DAS: potret beranda sekarang (judul, meta, H1/H2, kata kunci fokus) + usulan perbaikan."""
import base64, html, json, re, urllib.request, urllib.error, importlib.util
from xml.sax.saxutils import escape

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 = CFG["domain"]
USER, PASS = CFG.get("user"), CFG.get("pass")
AUTH = base64.b64encode(f"{USER}:{PASS}".encode()).decode() if USER and PASS else None
UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/124 Safari/537.36"}

print("=== 1. beranda live ===")
h = urllib.request.urlopen(urllib.request.Request(f"https://{DOM}/", headers=UA), timeout=90).read().decode("utf-8", "replace")
t = re.search(r"<title>(.*?)</title>", h, re.S)
d = re.search(r'<meta name="description" content="([^"]*)"', h)
can = re.search(r'<link rel="canonical" href="([^"]*)"', h)
print(f"   judul     : {html.unescape(t.group(1)).strip() if t else '-'}  ({(len(html.unescape(t.group(1)).strip()) if t else 0)} char)")
print(f"   meta      : ({(len(d.group(1)) if d else 0)} char) {html.unescape(d.group(1))[:160] if d else '-'}")
print(f"   canonical : {can.group(1) if can else '-'}")
h1 = [html.unescape(re.sub(r"<[^>]+>", "", x)).strip()[:80] for x in re.findall(r"<h1[^>]*>(.*?)</h1>", h, re.S)]
h2 = [html.unescape(re.sub(r"<[^>]+>", "", x)).strip()[:60] for x in re.findall(r"<h2[^>]*>(.*?)</h2>", h, re.S)]
print(f"   H1        : {h1}")
print(f"   H2        : {h2[:8]}")
teks = re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", " ", re.sub(r"<(script|style)[^>]*>.*?</\1>", " ", h, flags=re.S | re.I))))
print(f"   kata      : {len(teks.split())}")
print(f"   'DAS' muncul {len(re.findall(r'DAS', h))}x | 'Surabaya' {len(re.findall('Surabaya', h))}x | 'Bengkel' {len(re.findall('Bengkel', h, re.I))}x")
print(f"   cuplikan awal: {teks[:220]}")

print("\n=== 2. meta Yoast beranda (via XML-RPC) ===")
def rpc(method, params=()):
    def val(v):
        if isinstance(v, int):
            return f"<value><int>{v}</int></value>"
        if isinstance(v, list):
            return "<value><array><data>" + "".join(val(x) for x in v) + "</data></array></value>"
        if isinstance(v, dict):
            return "<value><struct>" + "".join(f"<member><name>{escape(str(k))}</name>{val(x)}</member>"
                                               for k, x in v.items()) + "</struct></value>"
        return f"<value><string>{escape(str(v))}</string></value>"
    body = ("<?xml version=\"1.0\"?><methodCall><methodName>" + method + "</methodName><params>" +
            "".join(f"<param>{val(p)}</param>" for p in params) + "</params></methodCall>").encode()
    r = urllib.request.Request(f"https://www.{DOM}/xmlrpc.php", data=body,
                               headers={"Content-Type": "text/xml", "User-Agent": "Mozilla/5.0",
                                        "Authorization": f"Basic {AUTH}"}, method="POST")
    try:
        with urllib.request.urlopen(r, timeout=150) as x:
            return x.read().decode("utf-8", "replace")
    except Exception as e:
        return f"ERR {str(e)[:80]}"

# cari ID beranda
ids = [int(x) for x in re.findall(r'page-id-(\d+)', h)] + [int(x) for x in re.findall(r'"page_id":(\d+)', h)]
print(f"   kandidat ID beranda dari HTML: {sorted(set(ids))[:4]}")
for pid in sorted(set(ids))[:2]:
    isi = rpc("wp.getPost", [1, USER, PASS, pid])
    for kunci in ("_yoast_wpseo_focuskw", "_yoast_wpseo_title", "_yoast_wpseo_metadesc"):
        mm = re.search(r"<member><name>key</name><value><string>" + re.escape(kunci) +
                       r"</string></value></member>\s*<member><name>value</name><value><string>(.*?)</string>", isi, re.S)
        if mm:
            print(f"   #{pid} {kunci:<24} {mm.group(1)[:110]}")
