#!/usr/bin/env python3
"""Cek status halaman yang baru dipindah ke trash + dampaknya (tautan masuk & menu)."""
import base64, importlib.util, json, re, 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"}


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(4)
    return {}


print("=== isi trash ===")
d = rest("/wp-json/wp/v2/pages?status=trash&per_page=50&_fields=id,slug,link,title,modified")
if isinstance(d, list):
    for x in d:
        print(f"   #{x['id']} {x['slug']} | {re.sub(r'<[^>]+>', '', str(x['title']['rendered']))[:60]} | {x['modified'][:16]}")
else:
    print("   gagal:", str(d)[:80])

print("\n=== status URL di depan ===")
for u in [f"https://www.{DOM}/tentang-kami/", f"https://www.{DOM}/"]:
    try:
        with urllib.request.urlopen(urllib.request.Request(u, headers=UA), timeout=60) as x:
            print(f"   HTTP {x.status} · {u}")
    except urllib.error.HTTPError as e:
        print(f"   HTTP {e.code} · {u}")
    except Exception as e:
        print(f"   GAGAL {str(e)[:40]} · {u}")

print("\n=== tautan masuk ke /tentang-kami/ dari konten ===")
hit = 0
for jenis in ("posts", "pages"):
    page = 1
    while True:
        dd = rest(f"/wp-json/wp/v2/{jenis}?per_page=100&page={page}&status=publish&context=edit&_fields=id,link,content")
        if not isinstance(dd, list) or not dd:
            break
        for x in dd:
            n = len(re.findall(r"tentang-kami", x["content"]["raw"], re.I))
            if n:
                hit += 1
                print(f"   {n}× {x['link'][:74]}")
        if len(dd) < 100:
            break
        page += 1
print(f"   total konten dengan tautan masuk: {hit}")

print("\n=== apakah menu di beranda masih menautkan halaman itu? ===")
try:
    t = urllib.request.urlopen(urllib.request.Request(f"https://www.{DOM}/", headers=UA), timeout=90).read().decode("utf-8", "replace")
    n = len(re.findall(r"tentang-kami", t, re.I))
    print(f"   tautan 'tentang-kami' di beranda: {n}")
    m2 = re.search(r".{120}tentang-kami.{80}", t, re.S)
    if m2:
        print("   contoh:", re.sub(r"\s+", " ", m2.group(0))[:220])
except Exception as e:
    print("   gagal:", str(e)[:60])
