#!/usr/bin/env python3
"""The Skin Code Clinic: on-page (judul/meta/H1), kecepatan berulang, penanda konversi, dan GBP/NAP."""
import html, re, time, urllib.request, urllib.error

UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124 Safari/537.36"}


def ambil(u):
    t0 = time.time()
    try:
        r = urllib.request.urlopen(urllib.request.Request(u, headers=UA), timeout=120)
        return r.status, r.read().decode("utf-8", "replace"), round(time.time() - t0, 2), dict(r.headers)
    except urllib.error.HTTPError as e:
        return e.code, "", round(time.time() - t0, 2), dict(e.headers)
    except Exception as e:
        return 0, str(e)[:60], round(time.time() - t0, 2), {}


print("=== 1. kecepatan (3 kali, apex vs www) ===")
for i in range(3):
    for u in ("https://theskincodeclinic.com/", "https://www.theskincodeclinic.com/"):
        st, isi, detik, h = ambil(u)
        print(f"   {i+1}. {u:<42} {st} | {detik:>6}s | {len(isi)//1024:>4} KB | cf={h.get('cf-cache-status')}")

print("\n=== 2. on-page beranda ===")
st, h, _, hd = ambil("https://www.theskincodeclinic.com/")
t = re.search(r"<title>(.*?)</title>", h, re.S)
d = re.search(r'<meta name="description" content="([^"]*)"', h)
can = re.search(r'<link rel="canonical" href="([^"]*)"', h)
print(f"   judul     : {t.group(1).strip() if t else '-'}  ({len(t.group(1).strip()) if t else 0} char)")
print(f"   meta desc : ({len(d.group(1)) if d else 0} char) {d.group(1)[:110] if d else 'TIDAK ADA'}")
print(f"   canonical : {can.group(1) if can else '-'}")
h1 = [html.unescape(re.sub(r"<[^>]+>", "", x)).strip()[:70] for x in re.findall(r"<h1[^>]*>(.*?)</h1>", h, re.S)]
h2 = [html.unescape(re.sub(r"<[^>]+>", "", x)).strip()[:52] for x in re.findall(r"<h2[^>]*>(.*?)</h2>", h, re.S)]
print(f"   H1        : {h1}")
print(f"   H2 ({len(h2)})   : {h2[:8]}")
teks_bersih = re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", " ", re.sub(r"<(script|style)[^>]*>.*?</\1>", " ", h, flags=re.S | re.I))))
print(f"   kata      : {len(teks_bersih.split())}")
print(f"   gambar    : {len(re.findall(r'<img', h))} | tanpa lazy: {len([m for m in re.findall(r'<img[^>]+>', h) if 'loading=' not in m])}")
print(f"   script    : {len(re.findall(r'<script', h))} | CSS: {len(re.findall(r'stylesheet', h))}")

print("\n=== 3. penanda konversi & kontak ===")
print("   wa.me     :", sorted(set(re.findall(r'wa\.me/(\d+)', h)))[:4] or "TIDAK ADA")
print("   tel:      :", sorted(set(re.findall(r'href="tel:([^"]+)"', h)))[:4] or "TIDAK ADA")
print("   GTM       :", sorted(set(re.findall(r'GTM-[A-Z0-9]{4,}', h))) or "tidak ada")
print("   GA4 tag   :", sorted(set(re.findall(r'G-[A-Z0-9]{6,}', h))) or "tidak ada")
print("   form      :", "ADA" if re.search(r"<form", h, re.I) else "tidak ada")
print("   maps      :", "ada" if "google.com/maps" in h else "tidak ada")
print("   schema    :", sorted(set(re.findall(r'"@type":\s*"([A-Za-z]+)"', h)))[:10])
print("   'Krian'   :", h.count("Krian"), "| 'Sidoarjo':", h.count("Sidoarjo"), "| 'DNI':", h.count("DNI"))

print("\n=== 4. halaman yang berimpresi tapi peringkatnya jauh ===")
for u in ("/dokter-kulit-kelamin-sidoarjo/", "/jadwal-dokter/", "/dermatologi-anak/", "/klinik-dni-krian-sidoarjo/"):
    st, hh, detik, _ = ambil(f"https://www.theskincodeclinic.com{u}")
    tt = re.search(r"<title>(.*?)</title>", hh, re.S) if hh else None
    dd = re.search(r'<meta name="description" content="([^"]*)"', hh) if hh else None
    print(f"   {st} | {u:<34} {detik}s | {tt.group(1).strip()[:58] if tt else ''}")
    print(f"        meta: {(len(dd.group(1)) if dd else 0)} char | kata: "
          f"{len(re.sub(chr(92)+'s+', ' ', html.unescape(re.sub(r'<[^>]+>', ' ', hh))).split()) if hh else 0}")
