#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Cari artikel studiosoft.id yang BELUM pernah dipakai di jadwal Repliz mana pun.

Pakai: python3 cari_artikel_belum_dipakai.py [kata-kunci]
  - artikel diambil dari /tmp/ss_articles.json (hasil fetch_ss_articles.py)
  - tiap artikel dicocokkan ke SELURUH jadwal (semua akun, semua status) lewat slug
"""
import json, re, sys, urllib.parse, urllib.request

sys.path.insert(0, "/home/mantapman/.hermes/profiles/atun/workspace")
from repliz_client import HEADERS, BASE

docs, page = [], 1
while True:
    q = urllib.parse.urlencode({"page": page, "limit": 100})
    req = urllib.request.Request(f"{BASE}/public/schedule?{q}", headers=HEADERS)
    with urllib.request.urlopen(req, timeout=60) as r:
        d = json.loads(r.read().decode())
    b = d.get("docs") or []
    docs += b
    if not b or page * 100 >= (d.get("totalDocs") or 0):
        break
    page += 1
blob = json.dumps(docs, ensure_ascii=False)
print("jadwal diperiksa:", len(docs))

arts = json.load(open("/tmp/ss_articles.json"))
kunci = [k.lower() for k in sys.argv[1:]]
belum = []
for a in arts:
    slug = a.get("slug") or ""
    judul = (a.get("title", {}) or {}).get("rendered", "")
    judul = re.sub(r"&#0?39;|&#8217;|&#038;", "'", judul)
    if slug and slug in blob:
        continue
    teks = (slug + " " + judul).lower()
    if kunci and not any(k in teks for k in kunci):
        continue
    belum.append((a.get("date", "")[:10], slug, judul, a.get("link")))

print(f"artikel belum dipakai (dan cocok filter {kunci or 'semua'}): {len(belum)}")
for d, s, j, l in belum:
    print(f"  {d} | {s[:52]:52} | {j[:60]}")
