#!/usr/bin/env python3
"""Pemeriksaan setelah Bos memperbarui WordPress TSC: versi, kesehatan halaman, sisa spam, dan
apakah perubahan kita (nomor, slug, pengalihan) masih utuh.
"""
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"}
SPAM = ["bohocasino", "moonwin", "jeetcity", "jeet-city", "winorio", "sasjen", "zonnepaneelconcurrent",
        "1883magazine", "engineeringimpact"]
LAMA = json.load(open(f"{WS}/drafts/tsc_slug_lama.json"))

print("=== 1. versi WordPress ===")
try:
    t = urllib.request.urlopen(urllib.request.Request(f"https://www.{DOM}/", headers=UA), timeout=90).read().decode("utf-8", "replace")
    v = re.search(r'content="WordPress ([0-9.]+)"', t)
    print("   generator:", v.group(1) if v else "(tidak tertulis)")
except Exception as e:
    print("   gagal:", str(e)[:60])

print("\n=== 2. halaman utama ===")
for u in ["https://www.theskincodeclinic.com/", "https://www.theskincodeclinic.com/faq-dokter-kulit-krian/",
          "https://www.theskincodeclinic.com/the-skin-code-clinic-spesialis-dermatologi-kelamin/",
          "https://www.theskincodeclinic.com/wp-json/wp/v2/posts?per_page=1"]:
    try:
        with urllib.request.urlopen(urllib.request.Request(u, headers=UA), timeout=60) as x:
            print(f"   HTTP {x.status} · {u.replace('https://www.theskincodeclinic.com', '')[:60]}")
    except urllib.error.HTTPError as e:
        print(f"   HTTP {e.code} · {u[-55:]}")
    except Exception as e:
        print(f"   GAGAL {str(e)[:40]} · {u[-45:]}")
    time.sleep(1)


def rest(path):
    h = {"Authorization": f"Basic {AUTH}", **UA}
    r = urllib.request.Request(f"https://{DOM}{path}", headers=h)
    for i in range(4):
        try:
            with urllib.request.urlopen(r, timeout=120) as x:
                return x.status, json.loads(x.read())
        except urllib.error.HTTPError as e:
            if e.code in (429, 404):
                time.sleep(4)
                continue
            return e.code, e.read().decode()[:150]
        except Exception:
            time.sleep(4)
    return 0, "gagal"


print("\n=== 3. sisa spam & nomor lama di seluruh konten ===")
spam_hit = nomor_hit = 0
for jenis in ("posts", "pages"):
    page = 1
    while True:
        st, 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:
            raw = x["content"]["raw"]
            s = [k for k in SPAM if k in raw.lower()]
            n = len(re.findall(r"6281335114324|6285194936363|0?812[\s\-]*[Xx]{2,}", raw))
            if s or n:
                print(f"   ⚠ #{x['id']} spam {s or '-'} · nomor lama {n} | {x['link'][:58]}")
                spam_hit += len(s)
                nomor_hit += n
        if len(d) < 100:
            break
        page += 1
        time.sleep(0.4)
print(f"   temuan spam: {spam_hit} · nomor lama/placeholder: {nomor_hit}")

print("\n=== 4. pengalihan & nomor di halaman (contoh) ===")
class TanpaAlih(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, *a, **k):
        return None


OP = urllib.request.build_opener(TanpaAlih)
for x in LAMA[:3]:
    try:
        OP.open(urllib.request.Request(x["link"], headers=UA), timeout=45)
        st = 200
    except urllib.error.HTTPError as e:
        st = e.code
    print(f"   {st} · {x['link'][-60:]}")
    time.sleep(0.8)
try:
    t2 = urllib.request.urlopen(urllib.request.Request("https://www.theskincodeclinic.com/", headers=UA), timeout=90).read().decode("utf-8", "replace")
    print(f"   nomor benar di beranda: {len(re.findall('6285117444417', t2))} · "
          f"nomor lama: {len(re.findall('6281335114324', t2))}")
except Exception as e:
    print("   gagal membaca beranda:", str(e)[:50])
