#!/usr/bin/env python3
"""Verifikasi keamanan SEO setelah slug diubah:
  1) URL lama → 301 → URL baru (satu lompatan, tidak berantai)
  2) URL baru → 200 dan memuat canonical ke dirinya sendiri
  3) tidak ada tautan internal yang masih menunjuk slug lama
  4) sitemap tidak lagi memuat slug lama
"""
import base64, importlib.util, json, re, sys, 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"}
LAMA = json.load(open(f"{WS}/drafts/tsc_slug_lama.json"))


def rest(path):
    h = {"Authorization": f"Basic {AUTH}", **UA}
    r = urllib.request.Request(f"https://{DOM}{path}", headers=h)
    for _ in range(3):
        try:
            with urllib.request.urlopen(r, timeout=120) as x:
                return json.loads(x.read())
        except urllib.error.HTTPError as e:
            return {"err": e.code}
        except Exception:
            time.sleep(3)
    return {}


class TanpaAlih(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, *a, **k):
        return None


OP = urllib.request.build_opener(TanpaAlih)


def status(url):
    try:
        with OP.open(urllib.request.Request(url, headers=UA), timeout=60) as x:
            return x.status, x.headers.get("Location"), x.read().decode("utf-8", "replace")
    except urllib.error.HTTPError as e:
        return e.code, e.headers.get("Location"), ""


print("=== 1 & 2. uji alamat lama dan baru ===")
masalah = []
ok = 0
for x in LAMA:
    o = rest(f"/wp-json/wp/v2/posts/{x['id']}?context=edit&_fields=id,slug,link")
    if not isinstance(o, dict) or "slug" not in o:
        masalah.append(f"#{x['id']} tidak bisa dibaca")
        continue
    if o["slug"] == x["slug"]:
        masalah.append(f"#{x['id']} slug TIDAK berubah (masih {o['slug'][:50]})")
        continue
    baru = o["link"]
    st_lama, loc, _ = status(x["link"])
    st_baru, _, html = status(baru)
    lompatan = 1 if (loc or "").rstrip("/") == baru.rstrip("/") else 0
    canonical = ""
    mc = re.search(r'<link rel="canonical" href="([^"]+)"', html)
    if mc:
        canonical = mc.group(1)
    canonical_ok = canonical.rstrip("/") == baru.rstrip("/")
    if st_lama == 301 and lompatan and st_baru == 200 and canonical_ok:
        ok += 1
    else:
        masalah.append(f"#{x['id']} lama={st_lama} loc={'ya' if lompatan else (loc or '-')} "
                       f"baru={st_baru} canonical={'ok' if canonical_ok else canonical[:60]}")
print(f"   beres: {ok} dari {len(LAMA)}   masalah: {len(masalah)}")
for s in masalah[:12]:
    print("   ⚠", s)

print("\n=== 3. tautan internal ke slug lama ===")
sisa = 0
for jenis in ("posts", "pages"):
    page = 1
    while True:
        d = rest(f"/wp-json/wp/v2/{jenis}?per_page=100&page={page}&status=publish&context=edit&_fields=id,link,content")
        if not isinstance(d, list) or not d:
            break
        for x in d:
            n = sum(len(re.findall(re.escape(y["slug"]), x["content"]["raw"])) for y in LAMA)
            if n:
                sisa += n
                print(f"   ⚠ {n}× {x['link'][:70]}")
        if len(d) < 100:
            break
        page += 1
print(f"   total tautan ke slug lama: {sisa}")

print("\n=== 4. sitemap ===")
try:
    idx = urllib.request.urlopen(urllib.request.Request(f"https://www.{DOM}/sitemap_index.xml", headers=UA),
                                 timeout=60).read().decode("utf-8", "replace")
    subs = re.findall(r"<loc>([^<]+)</loc>", idx)
    semua = ""
    for s in subs:
        if "post" in s or "page" in s:
            semua += urllib.request.urlopen(urllib.request.Request(s, headers=UA), timeout=60).read().decode("utf-8", "replace")
    urls = re.findall(r"<loc>([^<]+)</loc>", semua)
    lama_masih = [u for u in urls if re.search(r"klinik[\s-]*dni", u, re.I)]
    print(f"   entri sitemap diperiksa: {len(urls)} · masih memuat nama lama: {len(lama_masih)}")
    for u in lama_masih[:6]:
        print("   ⚠", u[:96])
except Exception as e:
    print("   gagal membaca sitemap:", str(e)[:70])
