#!/usr/bin/env python3
"""Cari lokasi suntikan di DAS: jenis konten kustom (WPCode, sliders) yang bisa memuat skrip ke semua halaman."""
import base64, importlib.util, json, re, time, urllib.error, urllib.request

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
spec = importlib.util.spec_from_file_location("cfg", f"{WS}/cfg_das.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"}
POLA = re.compile(r"livedashboardkit|35862e74a4a697bb6d998c471eade297|_b4a7b|track-", re.I)


def rest(path):
    r = urllib.request.Request(f"https://{DOM}{path}", headers={"Authorization": f"Basic {AUTH}", **UA})
    for i in range(3):
        try:
            with urllib.request.urlopen(r, timeout=120) as x:
                return json.loads(x.read())
        except urllib.error.HTTPError as e:
            return {"err": e.code, "msg": e.read().decode()[:120]}
        except Exception:
            time.sleep(4)
    return {}


print("=== jenis konten yang tersedia di REST ===")
types = rest("/wp-json/wp/v2/types")
if isinstance(types, dict) and "err" not in types:
    for k, v in types.items():
        print(f"   {k:<26} {str(v.get('name'))[:30]:<32} rest={v.get('rest_base')}")

print("\n=== cari skrip di seluruh jenis konten kustom ===")
kandidat = ["wpcode", "ihaf", "snippets", "custom-css-js", "simple-css", "page", "rev_slider", "wpcf7_contact_form"]
for base in kandidat:
    d = rest(f"/wp-json/wp/v2/{base}?per_page=50&context=edit" if base != "wpcode" else "/wp-json/wp/v2/wpcode?per_page=50&context=edit")
    if isinstance(d, list):
        print(f"   {base}: {len(d)} entri")
        for x in d[:10]:
            isi = json.dumps(x, ensure_ascii=False)
            if POLA.search(isi):
                print(f"      ⚠ #{x.get('id')} {(x.get('title') or {}).get('raw') or (x.get('title') or {}).get('rendered')}")
    elif isinstance(d, dict) and d.get("err"):
        print(f"   {base}: HTTP {d['err']}")

print("\n=== pengaturan WPCode (kalau bisa dibaca) ===")
for path in ("/wp-json/wp/v2/settings", "/wp-json/ihaf/v1/settings"):
    d = rest(path)
    if isinstance(d, dict) and "err" not in d:
        print(f"   {path} → {list(d)[:12]}")
