#!/usr/bin/env python3
"""TSC: cek kecepatan/ketersediaan beranda (www vs apex) dan status pass tautan internal."""
import base64, json, re, time, urllib.request, urllib.error, importlib.util

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/124 Safari/537.36"}

print("=== 1. beranda: www vs apex (5 percobaan) ===")
for i in range(5):
    for u in ("https://www.theskincodeclinic.com/", "https://theskincodeclinic.com/"):
        t0 = time.time()
        try:
            r = urllib.request.urlopen(urllib.request.Request(u, headers=UA), timeout=45)
            b = r.read()
            print(f"   {i+1}. {u:<40} {r.status} | {round(time.time()-t0,2):>6}s | {len(b)//1024:>4} KB | cf={r.headers.get('cf-cache-status')}")
        except urllib.error.HTTPError as e:
            print(f"   {i+1}. {u:<40} HTTP {e.code} | {round(time.time()-t0,2)}s | lokasi={str(e.headers.get('Location'))[:40]}")
        except Exception as e:
            print(f"   {i+1}. {u:<40} ERR {round(time.time()-t0,2)}s | {str(e)[:40]}")

print("\n=== 2. halaman lain sebagai pembanding ===")
for u in ("https://www.theskincodeclinic.com/faq-dokter-kulit-krian/",
          "https://www.theskincodeclinic.com/articles/",
          "https://www.theskincodeclinic.com/tentang-kami/"):
    t0 = time.time()
    try:
        r = urllib.request.urlopen(urllib.request.Request(u, headers=UA), timeout=45)
        print(f"   {r.status} | {round(time.time()-t0,2):>6}s | {u.replace('https://www.theskincodeclinic.com','')}")
    except Exception as e:
        print(f"   ERR | {round(time.time()-t0,2)}s | {u} ({str(e)[:40]})")

print("\n=== 3. status pass tautan internal (latar belakang) ===")
spec = importlib.util.spec_from_file_location("cfg_tsc", f"{WS}/cfg_tsc.py")
m = importlib.util.module_from_spec(spec); spec.loader.exec_module(m)
AUTH = base64.b64encode(f'{m.CFG["user"]}:{m.CFG["pass"]}'.encode()).decode()


def rest(p):
    r = urllib.request.Request(f'https://{m.CFG["domain"]}{p}', headers={"Authorization": f"Basic {AUTH}", **UA})
    for _ in range(3):
        try:
            with urllib.request.urlopen(r, timeout=150) as x:
                return json.loads(x.read())
        except Exception:
            time.sleep(3)
    return []


punya = total = 0
page = 1
while True:
    d = rest(f"/wp-json/wp/v2/posts?per_page=100&page={page}&status=publish&context=edit&_fields=id,content")
    if not isinstance(d, list):
        break
    for p in d:
        total += 1
        raw = p.get("content", {}).get("raw", "") if isinstance(p.get("content"), dict) else ""
        if "baca juga" in raw.lower():
            punya += 1
    if len(d) < 100:
        break
    page += 1
print(f"   artikel dengan blok 'Baca juga': {punya} dari {total}")
