#!/usr/bin/env python3
"""Pemantau harian TSC: memeriksa isi situs untuk tautan spam tersembunyi dan nomor lama.

Diam kalau bersih (stdout kosong = tidak ada pesan ke Bos). Berbunyi hanya kalau ada temuan.
"""
import base64, importlib.util, json, re, sys, 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"}

SPAM = ["bohocasino", "moonwin", "jeetcity", "jeet-city", "winorio", "sasjen", "zonnepaneelconcurrent",
        "1883magazine", "engineeringimpact", "slot88", "maxwin", "togel", "judi online", "situs slot",
        "bandar togel", "casino online"]
# catatan: kata generik seperti "dewa" (bisa cocok dengan "dewasa") dan "slot" tidak dipakai
# supaya tidak memunculkan temuan palsu.
NOMOR_LAMA = re.compile(r"6281335114324|6285194936363|0?812[\s\-]*[Xx]{2,}[\s\-]*[Xx]{2,}")
SEMBUNYI = re.compile(r'(position:\s*absolute;\s*left:\s*-\d{3,}|overflow:\s*hidden;\s*height:\s*1px)', re.I)
TAUTAN_LUAR = re.compile(r'href="https?://(?!www\.theskincodeclinic|theskincodeclinic|wa\.me|api\.whatsapp|www\.google|goo\.gl|maps\.)[^"]+"', re.I)


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=120) as x:
                return json.loads(x.read())
        except urllib.error.HTTPError as e:
            if e.code in (429, 404):
                time.sleep(4 * (i + 1))
                continue
            return {"err": e.code}
        except Exception:
            time.sleep(4)
    return {}


temuan = []
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:
            raw = x["content"]["raw"]
            spam = sorted({k for k in SPAM if k in raw.lower()})
            nomor = len(NOMOR_LAMA.findall(raw))
            sembunyi = len(SEMBUNYI.findall(raw))
            luar = len(set(TAUTAN_LUAR.findall(raw)))
            # elemen tersembunyi + tautan ke luar = pola injeksi; tautan luar biasa (mis. Pexels) tidak dihitung
            curiga = sembunyi if (sembunyi and luar) else 0
            if spam or nomor or curiga:
                temuan.append({"jenis": jenis, "id": x["id"], "link": x["link"],
                               "spam": spam, "nomor": nomor, "sembunyi": curiga,
                               "luar": luar if curiga else 0})
        if len(d) < 100:
            break
        page += 1
        time.sleep(0.3)

if not temuan:
    sys.exit(0)          # bersih → diam

print("⚠️ *TSC — temuan pemantauan harian*")
for t in temuan[:10]:
    rincian = []
    if t["spam"]:
        rincian.append(f"tautan spam: {', '.join(t['spam'][:4])}")
    if t["nomor"]:
        rincian.append(f"nomor lama/placeholder: {t['nomor']}")
    if t["sembunyi"]:
        rincian.append(f"elemen disembunyikan: {t['sembunyi']}")
    print(f"• {t['link']}")
    print(f"   {' · '.join(rincian)}")
if len(temuan) > 10:
    print(f"… dan {len(temuan) - 10} halaman lain")
print("\nPembersihnya: `python3 tsc_bersih_spam.py --go` (workspace).")
