#!/usr/bin/env python3
"""Tampilkan gambar pustaka media TSLaw yang belum dipakai, untuk dipilih sebagai gambar unggulan."""
import base64, json, re, time, urllib.error, urllib.request

SITUS = "https://www.tslaw.id"
AUTH = base64.b64encode(b"bambangbot:EFKm EYGx VQCP Y9go ncPr uM2Y").decode()
H = {"Authorization": f"Basic {AUTH}", "User-Agent": "Mozilla/5.0"}


def rest(path):
    r = urllib.request.Request(f"{SITUS}{path}", headers=H)
    for i in range(3):
        try:
            with urllib.request.urlopen(r, timeout=120) as x:
                return json.loads(x.read())
        except Exception:
            time.sleep(4)
    return {}


posts = rest("/wp-json/wp/v2/posts?per_page=100&status=publish&_fields=id,featured_media")
dipakai = {p["featured_media"] for p in posts if p.get("featured_media")}

med, page = [], 1
while True:
    d = rest(f"/wp-json/wp/v2/media?per_page=100&page={page}&orderby=date&order=desc&_fields=id,source_url,title,media_details")
    if not isinstance(d, list) or not d:
        break
    med += d
    if len(d) < 100:
        break
    page += 1

bebas = []
for x in med:
    if x["id"] in dipakai or not str(x.get("source_url", "")).lower().endswith((".jpg", ".jpeg", ".png", ".webp")):
        continue
    md = x.get("media_details") or {}
    judul = re.sub(r"<[^>]+>", "", str((x.get("title") or {}).get("rendered", "")))
    bebas.append({"id": x["id"], "nama": x["source_url"].split("/")[-1], "judul": judul,
                  "ukuran": f"{md.get('width')}x{md.get('height')}"})

print(f"gambar belum dipakai: {len(bebas)}\n")
KATA = ("law", "hukum", "kantor", "konsultan", "advokat", "meeting", "rapat", "dokumen", "kontrak",
        "bisnis", "perusahaan", "surabaya", "gedung", "office", "legal", "client", "handshake")
prioritas = sorted(bebas, key=lambda x: -sum(1 for k in KATA if k in (x["nama"] + " " + x["judul"]).lower()))
for x in prioritas[:30]:
    skor = sum(1 for k in KATA if k in (x["nama"] + " " + x["judul"]).lower())
    print(f"   #{x['id']:<5} {x['ukuran']:<10} skor {skor} · {x['nama'][:58]}")
