#!/usr/bin/env python3
"""Cari foto di pustaka media TSC yang belum dipakai sebagai gambar unggulan dan cocok temanya."""
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_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"}


def rest(path):
    h = {"Authorization": f"Basic {AUTH}", **UA}
    r = urllib.request.Request(f"https://{DOM}{path}", headers=h)
    for _ 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)
                continue
            return {"err": e.code}
        except Exception:
            time.sleep(4)
    return {}


# gambar yang sudah dipakai
dipakai = set()
for jenis in ("posts", "pages"):
    page = 1
    while True:
        d = rest(f"/wp-json/wp/v2/{jenis}?per_page=100&page={page}&status=publish&_fields=id,featured_media")
        if not isinstance(d, list) or not d:
            break
        for x in d:
            if x.get("featured_media"):
                dipakai.add(x["featured_media"])
        if len(d) < 100:
            break
        page += 1
print(f"gambar yang sudah dipakai sebagai unggulan: {len(dipakai)}")

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

bebas = [x for x in med if x["id"] not in dipakai and x.get("mime_type", "").startswith("image/")]
print(f"media belum dipakai: {len(bebas)}\n")

KATA = ("klinik", "clinic", "konsultasi", "consult", "dokter", "doctor", "kulit", "skin", "wajah", "facial",
        "perawatan", "treatment", "pasien", "patient", "ruang", "room", "resep", "obat", "medical", "medis")

kandidat = []
for x in bebas:
    t = (str(x.get("title", {}).get("rendered", "")) + " " + x["source_url"]).lower()
    skor = sum(1 for k in KATA if k in t)
    kandidat.append((skor, x))
kandidat.sort(key=lambda y: -y[0])

print("=== 15 kandidat terbaik ===")
for skor, x in kandidat[:15]:
    judul = re.sub(r"<[^>]+>", "", str(x.get("title", {}).get("rendered", "")))[:52]
    print(f"  skor {skor:>2} | #{x['id']:<6} | {judul:<54} | {x['source_url'][-56:]}")

json.dump([{"id": s[1]["id"], "titile": s[1]["title"], "url": s[1]["source_url"], "skor": s[0]}
           for s in kandidat[:40]], open(f"{WS}/drafts/tsc_kandidat_gambar.json", "w"), ensure_ascii=False, indent=1)
