#!/usr/bin/env python3
"""Bedah situs sampoernajayabaja.com: profil, layanan, kontak, sosial media, dan keadaan teknisnya."""
import html, json, re, time, urllib.parse, urllib.request, urllib.error

UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36",
      "Accept-Language": "id-ID,id;q=0.9"}
DOM = "https://sampoernajayabaja.com"


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


def bersih(t):
    t = re.sub(r"<script.*?</script>|<style.*?</style>", " ", t, flags=re.S | re.I)
    return html.unescape(re.sub(r"<[^>]+>", " ", t)).strip()


st, h, detik, head = ambil(DOM + "/")
print(f"=== beranda ===\n   status {st} | {detik:.1f}s | {len(h)} byte | server: {head.get('server')}")
judul = re.search(r"<title[^>]*>(.*?)</title>", h, re.S)
print(f"   judul  : {bersih(judul.group(1))[:120] if judul else '-'}")
desc = re.search(r'<meta[^>]+name="description"[^>]+content="([^"]*)"', h, re.I)
print(f"   meta   : {desc.group(1)[:200] if desc else '(tidak ada)'}")
print("   platform:", sorted(set(re.findall(r"/wp-content/(?:themes|plugins)/([a-z0-9\-_]+)", h)))[:8] or "bukan WordPress?")

print("\n=== kontak & identitas yang tertulis ===")
pola = {
    "telepon/WA": r"(?:\+?62|0)8\d{1,3}[\s\-]?\d{3,4}[\s\-]?\d{3,5}",
    "telepon tetap": r"\(?0\d{2,3}\)?[\s\-]?\d{3,4}[\s\-]?\d{3,4}",
    "email": r"[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-z]{2,}",
    "wa.me": r"wa\.me/\d+",
    "alamat kandidat": r"(?:jl\.?|jalan|kawasan|kav|blok|ruko|gudang)[^<\n]{0,90}",
    "npwp/nib": r"(?:npwp|nib|akta)[^<\n]{0,60}",
}
for nama, p in pola.items():
    hasil = sorted(set(re.findall(p, h, re.I)))[:6]
    print(f"   {nama:<16}: {hasil if hasil else '-'}")

print("\n=== tautan sosial & luar ===")
luar = sorted(set(re.findall(r'href="(https?://(?!sampoernajayabaja)[^"]+)"', h)))
for u in luar[:25]:
    print("   " + u[:110])

print("\n=== halaman yang ada ===")
st2, sm, _, _ = ambil(DOM + "/sitemap.xml")
if st2 == 200:
    lok = re.findall(r"<loc>([^<]+)</loc>", sm)
    print(f"   sitemap: {len(lok)} URL")
    for u in lok[:30]:
        print("      " + u.replace(DOM, "")[:100])
else:
    st3, sm2, _, _ = ambil(DOM + "/sitemap_index.xml")
    if st3 == 200:
        for sub in re.findall(r"<loc>([^<]+)</loc>", sm2)[:6]:
            st4, ss, _, _ = ambil(sub)
            print(f"   {sub.replace(DOM, '')}: {len(re.findall(r'<loc>', ss))} URL")
            for u in re.findall(r"<loc>([^<]+)</loc>", ss)[:15]:
                print("      " + u.replace(DOM, "")[:100])
    else:
        print("   sitemap tidak ditemukan (coba /robots.txt untuk daftarnya)")

st5, rb, _, _ = ambil(DOM + "/robots.txt")
print("\n=== robots.txt ===")
print("   " + rb.replace("\n", "\n   ")[:400] if st5 == 200 else f"   status {st5}")

print("\n=== pelacak & tombol WhatsApp ===")
print("   GA4    :", sorted(set(re.findall(r"G-[A-Z0-9]{8,}", h))) or "tidak ada")
print("   GTM    :", sorted(set(re.findall(r"GTM-[A-Z0-9]+", h))) or "tidak ada")
print("   FB pixel:", len(re.findall(r"connect\.facebook\.net", h)), "| gtag:", len(re.findall(r"googletagmanager", h)))
print("   tautan WA:", len(re.findall(r"wa\.me|api\.whatsapp", h, re.I)))
