#!/usr/bin/env python3
"""Bedah halaman DAS yang tidak bisa dibuka: cari pengalihan skrip, iframe, dan isi mencurigakan."""
import re, time, urllib.error, urllib.request

URL = "https://dasindonesia.com/merawat-sistem-pendingin-mesin-radiator-cairan/"
UA_BROWSER = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36",
              "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
              "Accept-Language": "id-ID,id;q=0.9,en;q=0.8"}
UA_GOOGLE = {"User-Agent": "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"}
UA_PLAIN = {"User-Agent": "curl/8.5.0"}


def ambil(kepala, label):
    try:
        r = urllib.request.Request(URL, headers=kepala)
        t0 = time.time()
        with urllib.request.urlopen(r, timeout=60) as x:
            body = x.read().decode("utf-8", "replace")
            dur = time.time() - t0
        return x.status, body, dict(x.headers), dur, label
    except urllib.error.HTTPError as e:
        return e.code, e.read().decode("utf-8", "replace")[:500], dict(e.headers), 0, label
    except Exception as e:
        return "GAGAL", str(e)[:80], {}, 0, label


for kepala, label in ((UA_BROWSER, "browser"), (UA_GOOGLE, "googlebot"), (UA_PLAIN, "curl")):
    st, body, hdr, dur, lab = ambil(kepala, label)
    print(f"\n=== {lab} · HTTP {st} · {len(body) if isinstance(body, str) else 0} char · {dur:.2f}s ===")
    if not isinstance(body, str) or len(body) < 200:
        print("   isi:", str(body)[:200])
        continue
    judul = re.search(r"<title>(.*?)</title>", body, re.S)
    print("   judul:", re.sub(r"\s+", " ", judul.group(1)).strip()[:90] if judul else "-")
    print("   server:", hdr.get("Server"), "| cf-cache:", hdr.get("cf-cache-status"))

    pola = {
        "meta refresh": r'<meta[^>]+http-equiv=["\']refresh["\'][^>]*>',
        "pengalihan JS": r"(?:window|document)\.location[^;]{0,80}",
        "iframe": r'<iframe[^>]*src=["\']([^"\']+)["\']',
        "elemen tersembunyi": r'(?:position:\s*absolute;\s*left:\s*-\d+|overflow:\s*hidden;\s*height:\s*1px)',
        "kata judi": r"(?:casino|slot|togel|maxwin|gacor|judi)",
        "skrip luar": r'<script[^>]+src=["\']([^"\']+)["\']',
    }
    for nama, p in pola.items():
        m = re.findall(p, body, re.I)
        if m:
            print(f"   {nama}: {len(m)} → {str(m[:3])[:150]}")

    # apakah isi artikelnya benar-benar ada
    teks = re.sub(r"<script.*?</script>|<style.*?</style>", " ", body, flags=re.S)
    teks = re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", teks))
    print("   panjang teks terlihat:", len(teks))
    print("   cuplikan:", teks[:220].strip())
    time.sleep(1)
