#!/usr/bin/env python3
"""Cek calon topik artikel baru terhadap SELURUH artikel StudioSoft (kanibalisasi).

Pakai: python3 ss_cek_topik.py "Judul calon" ["kata kunci fokus"]
Keluar kode 1 kalau ada artikel lama yang terlalu mirip (>= 0,30) atau fokusnya sama.
Peta artikel di-cache 6 jam di drafts/ss_peta_artikel.json supaya tidak menarik ulang terus.
"""
import base64, html, json, os, re, sys, time, urllib.error, urllib.request
from datetime import datetime, timezone

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
S = "https://studiosoft.id"
AUTH = base64.b64encode(b"bambangbot:q26r RePo BVy6 pwU2 F3z7 ouyl").decode()
UA = {"User-Agent": "Mozilla/5.0"}
CACHE = f"{WS}/drafts/ss_peta_artikel.json"
STOP = set("""yang untuk dan dari dengan pada dalam adalah ini itu cara tips panduan lengkap penting
mengapa kenapa bagaimana di ke atau agar supaya bisnis usaha surabaya indonesia 2026 jasa kamu anda
bikin buat tanpa juga bisa akan sudah belum lebih paling serta para oleh ada""".split())


def rest(path):
    h = {"Authorization": f"Basic {AUTH}", **UA}
    r = urllib.request.Request(S + path, headers=h)
    for _ in range(3):
        try:
            with urllib.request.urlopen(r, timeout=180) as x:
                return json.loads(x.read())
        except urllib.error.HTTPError as e:
            return {"err": e.code}
        except Exception:
            time.sleep(4)
    return {}


def segar():
    if not os.path.exists(CACHE):
        return False
    return (time.time() - os.path.getmtime(CACHE)) < 6 * 3600


def tarik():
    peta, page = [], 1
    for status in ("publish", "future", "draft"):
        page = 1
        while True:
            d = rest(f"/wp-json/wp/v2/posts?status={status}&per_page=100&page={page}&context=edit"
                     f"&_fields=id,slug,status,title,meta")
            if not isinstance(d, list) or not d:
                break
            peta += [{"id": p["id"], "slug": p["slug"], "status": p["status"],
                      "judul": html.unescape(p["title"]["raw"]),
                      "fokus": ((p.get("meta") or {}).get("_yoast_wpseo_focuskw") or "").strip()}
                     for p in d]
            if len(d) < 100:
                break
            page += 1
    json.dump(peta, open(CACHE, "w"), ensure_ascii=False, indent=1)
    return peta


def kunci(teks):
    return {w for w in re.findall(r"[a-z]{4,}", teks.lower()) if w not in STOP}


def jaccard(a, b):
    return len(a & b) / max(1, len(a | b))


peta = tarik() if not segar() else json.load(open(CACHE))
judul = sys.argv[1] if len(sys.argv) > 1 else ""
fokus = sys.argv[2] if len(sys.argv) > 2 else ""
if not judul:
    print("pakai: python3 ss_cek_topik.py \"Judul calon\" [\"fokus\"]")
    sys.exit(2)

k = kunci(judul + " " + fokus)
skor = sorted(((jaccard(k, kunci(p["judul"] + " " + p["fokus"])), p) for p in peta), key=lambda x: -x[0])
print(f"calon : «{judul}» · fokus «{fokus}»")
print(f"diperiksa terhadap {len(peta)} artikel (terbit + terjadwal + draf)\n")
bahaya = []
for s, p in skor[:5]:
    tanda = " ⚠" if s >= 0.30 or (fokus and p["fokus"].lower() == fokus.lower()) else ""
    print(f"  {s:.2f} #{p['id']:>5} [{p['status']:<8}] {p['judul'][:56]}{tanda}")
    if tanda:
        bahaya.append(p)
if bahaya:
    print(f"\nHASIL: BENTURAN — {len(bahaya)} artikel mirip. Ganti sudut atau judulnya.")
    sys.exit(1)
print("\nHASIL: aman, belum ada yang mirip.")
