#!/usr/bin/env python3
"""Cek kesehatan tslaw.id + struktur permalink + kanibalisasi calon artikel pencemaran nama baik."""
import base64, json, re, urllib.request, urllib.error, time

DOM = "tslaw.id"
USER, PASS = "bambangbot", "EFKm EYGx VQCP Y9go ncPr uM2Y"
AUTH = base64.b64encode(f"{USER}:{PASS}".encode()).decode()
UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/124 Safari/537.36"}


def rest(path, method="GET", data=None):
    h = {"Authorization": f"Basic {AUTH}", **UA}
    body = None
    if data is not None:
        body = json.dumps(data).encode()
        h["Content-Type"] = "application/json"
    r = urllib.request.Request(f"https://{DOM}{path}", data=body, headers=h, method=method)
    for i in range(3):
        try:
            with urllib.request.urlopen(r, timeout=120) as x:
                return x.status, json.loads(x.read())
        except urllib.error.HTTPError as e:
            return e.code, e.read().decode()[:300]
        except Exception as e:
            print(f"    (ulang {i+1}: {str(e)[:60]})")
            time.sleep(5)
    return 0, "gagal"


def head(url):
    req = urllib.request.Request(url, headers=UA)
    try:
        with urllib.request.urlopen(req, timeout=60) as x:
            return x.status, x.geturl()
    except urllib.error.HTTPError as e:
        return e.code, url
    except Exception as e:
        return f"ERR {str(e)[:50]}", url


print("=== KESEHATAN SITUS ===")
for u in ["https://www.tslaw.id/", "https://tslaw.id/", "https://www.tslaw.id/layanan/",
          "https://www.tslaw.id/hubungi/", "https://www.tslaw.id/wp-json/"]:
    st, fin = head(u)
    print(f"  {st}  {u}  -> {fin}")

# zona waktu + permalink contoh
st, root = rest("/wp-json/")
if isinstance(root, dict):
    print(f"\n  timezone: {root.get('timezone_string')} | gmt_offset: {root.get('gmt_offset')}")

print("\n=== CONTOH LINK POST TERBARU (struktur permalink) ===")
st, posts = rest("/wp-json/wp/v2/posts?per_page=5&status=publish,future,draft&orderby=date&order=desc&_fields=id,slug,link,status,date")
if isinstance(posts, list):
    for p in posts:
        print(f"  #{p['id']} [{p['status']}] {p['link']}")

print("\n=== SJUMLAH POST PER STATUS ===")
for s in ["publish", "future", "draft"]:
    st, hh = rest(f"/wp-json/wp/v2/posts?status={s}&per_page=1")
    tot = None
    # ambil total dari header tidak tersedia lewat fungsi ini; pakai count halaman besar
    st2, allp = rest(f"/wp-json/wp/v2/posts?status={s}&per_page=100&_fields=id")
    print(f"  {s}: {len(allp) if isinstance(allp, list) else allp}")

# kanibalisasi: tarik semua post publish+future+draft, bandingkan token
print("\n=== KANIBALISASI CALON 'pengacara pencemaran nama baik surabaya' ===")
calon_judul = "6 Pengacara Pencemaran Nama Baik dan UU ITE di Surabaya"
calon_slug = "pengacara-pencemaran-nama-baik-surabaya"
calon_fokus = "pengacara pencemaran nama baik surabaya"


def tok(t):
    return set(w for w in re.findall(r"[a-z0-9]+", t.lower()) if len(w) > 2)


tc = tok(calon_judul) | tok(calon_slug) | tok(calon_fokus)
semua = []
for s in ["publish", "future", "draft"]:
    st, page = rest(f"/wp-json/wp/v2/posts?status={s}&per_page=100&context=edit&_fields=id,slug,title,status,meta&page=1")
    if isinstance(page, list):
        semua += page
    time.sleep(1)
print(f"  total artikel diperiksa: {len(semua)}")
hasil = []
for p in semua:
    judul = p.get("title", {}).get("raw", "") if isinstance(p.get("title"), dict) else str(p.get("title"))
    fokus = ""
    if isinstance(p.get("meta"), dict):
        fokus = p["meta"].get("_yoast_wpseo_focuskw", "") or ""
    tt = tok(judul) | tok(p.get("slug", "")) | tok(fokus)
    if not tt:
        continue
    j = len(tc & tt) / len(tc | tt)
    if j >= 0.20 or (fokus and fokus.strip().lower() == calon_fokus):
        hasil.append((round(j, 3), p["id"], p.get("status"), fokus, judul[:70], p.get("slug")))
for h in sorted(hasil, reverse=True)[:12]:
    print(f"  skor {h[0]:>5} #{h[1]} [{h[2]}] fokus='{h[3]}' | {h[4]} | /{h[5]}")
