#!/usr/bin/env python3
"""Pemeriksaan akhir TSC: sisa nama lama di konten, contoh pengalihan, dan tampilan live."""
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"}
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 i in range(4):
        try:
            with urllib.request.urlopen(r, timeout=90) as x:
                return json.loads(x.read())
        except urllib.error.HTTPError as e:
            if e.code in (429, 404):
                time.sleep(4)
                continue
            return {"err": e.code}
        except Exception:
            time.sleep(4)
    return {}


print("=== A. sisa nama lama di seluruh konten ===")
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: {sisa}")

print("\n=== B. contoh pengalihan (5 artikel) ===")
class TanpaAlih(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, *a, **k):
        return None


OP = urllib.request.build_opener(TanpaAlih)
for x in LAMA[:5]:
    o = rest(f"/wp-json/wp/v2/posts/{x['id']}?_fields=id,link")
    if not isinstance(o, dict):
        continue
    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'][:74]}")
    time.sleep(0.8)

print("\n=== C. tampilan live (tautan lama sudah berubah?) ===")
for u in ["https://www.theskincodeclinic.com/", "https://www.theskincodeclinic.com/tentang-kami/",
          "https://www.theskincodeclinic.com/perawatan-wajah-terbaik-di-sidoarjo/"]:
    try:
        with urllib.request.urlopen(urllib.request.Request(u, headers=UA), timeout=60) as x:
            t = x.read().decode("utf-8", "replace")
        lama = len(re.findall(r"klinik-dni|klinikdni", t, re.I))
        print(f"   HTTP {x.status} · nama lama di HTML: {lama} · {u.replace('https://www.theskincodeclinic.com', '') or '/'}")
    except urllib.error.HTTPError as e:
        print(f"   HTTP {e.code} · {u[-50:]}")
    except Exception as e:
        print(f"   GAGAL {str(e)[:40]} · {u[-40:]}")
    time.sleep(1)
