#!/usr/bin/env python3
"""Pass 2 link internal LEIT: 13 URL yang belum dikenal Google harus punya penaut masuk.
Menambah <li> ke blok 'Baca Juga' yang sudah ada (maks 5 item/blok). Idempoten."""
import base64, html, json, re, sys, urllib.request, urllib.error

SITE = "https://www.leitsurabaya.com"
AUTH = base64.b64encode(b"bambangbot:zibd dLIV xY8x onP9 39qL hiNr").decode()

TARGET = {
    4147: "bahasa Inggris untuk anak dengan metode seru",
    4145: "frasa bahasa Inggris penting untuk traveling",
    4143: "panduan bahasa Inggris untuk beasiswa",
    4141: "contoh pertanyaan wawancara kerja bahasa Inggris",
    4139: "cara cepat menghafal kosakata bahasa Inggris",
    4059: "jangan nunggu siap untuk mulai belajar Inggris",
    4051: "belajar bahasa Inggris untuk dewasa",
    3928: "kursus bahasa Inggris di Surabaya Timur",
    3925: "kursus bahasa Inggris di Surabaya Barat",
    3904: "alasan les bahasa Inggris terdekat dari rumah",
    3903: "7 tempat les bahasa Inggris terdekat di Surabaya",
    3902: "les bahasa Inggris terdekat di Surabaya",
    3864: "soft skills yang dicari di era AI",
}
STOP = set("dan yang untuk dari dengan pada di ke the a an of to in and or ini itu bisa gak tidak leit".split())


def api(path, data=None, method="GET"):
    h = {"Authorization": f"Basic {AUTH}", "User-Agent": "Mozilla/5.0"}
    body = None
    if data is not None:
        body = json.dumps(data).encode()
        h["Content-Type"] = "application/json"
    r = urllib.request.Request(SITE + path, data=body, headers=h, method=method)
    try:
        with urllib.request.urlopen(r, timeout=240) as x:
            return x.status, json.loads(x.read())
    except urllib.error.HTTPError as e:
        return e.code, e.read().decode()[:200]


posts, page = [], 1
while True:
    st, d = api(f"/wp-json/wp/v2/posts?per_page=100&page={page}&context=edit&_fields=id,link,slug,title,content")
    posts += d
    if len(d) < 100:
        break
    page += 1
print("artikel:", len(posts))
idx = {p["id"]: p for p in posts}
urlmap = {p["id"]: p["link"] for p in posts}


def toks(s):
    return {w for w in re.findall(r"[a-zA-Z]{4,}", html.unescape(re.sub(r"<[^>]+>", " ", s)).lower()) if w not in STOP}


plan = {}
for p in posts:
    pid = p["id"]
    raw = p["content"]["raw"]
    kini = set(re.findall(r'href="(https://www\.leitsurabaya\.com/[^"#?]+)"', raw))
    src = toks(p["title"]["rendered"] + " " + p["slug"])
    kandidat = []
    for t, anchor in TARGET.items():
        if t == pid or urlmap[t] in kini:
            continue
        tt = toks(idx[t]["title"]["rendered"] + " " + idx[t]["slug"])
        kandidat.append((len(src & tt), t, urlmap[t], anchor))
    kandidat.sort(reverse=True)
    pilih = kandidat[:2]
    if pilih:
        plan[pid] = pilih

print("artikel yang akan ditambah link (pass 2):", len(plan))
for pid, pilih in list(plan.items())[:6]:
    print(f"  #{pid} {idx[pid]['title']['rendered'][:48]}")
    for sk, t, url, anc in pilih:
        print(f"     skor {sk} → #{t} {anc}")

if "--apply" not in sys.argv:
    print("\n(dry run)")
    sys.exit(0)

ok = gagal = 0
for pid, pilih in plan.items():
    raw = idx[pid]["content"]["raw"]
    m = re.search(r"(<h2>\s*Baca Juga\s*</h2>\s*<ul>)(.*?)(</ul>)", raw, re.S | re.I)
    if m:
        isi = m.group(2)
        n = isi.count("<li>")
        sisa = max(0, 5 - n)
        if sisa == 0:
            print(f"  #{pid} skip (blok sudah {n} item)")
            continue
        items = [f'<li><a href="{url}">{anc}</a></li>' for s, t, url, anc in pilih][:sisa]
        baru = raw[:m.end(2)] + "\n" + "\n".join(items) + "\n" + raw[m.end(2):]
    else:
        items = [f'<li><a href="{url}">{anc}</a></li>' for s, t, url, anc in pilih]
        blok = "\n<h2>Baca Juga</h2>\n<ul>" + "\n".join(items) + "</ul>\n"
        mm = re.search(r"\n<h2>\s*Kesimpulan", raw, re.I)
        baru = (raw[:mm.start()] + blok + raw[mm.start():]) if mm else (raw.rstrip() + "\n" + blok)
    st, res = api(f"/wp-json/wp/v2/posts/{pid}", {"content": baru}, "POST")
    body = json.dumps(res) if isinstance(res, dict) else ""
    cek = all(url in body for s, t, url, anc in pilih)
    print(f"  #{pid} POST {st} | link tersimpan: {'Y' if cek else 'N'}")
    ok += 1 if cek else 0
    gagal += 0 if cek else 1
print(f"\npass 2 selesai: {ok} ok | {gagal} gagal")
