#!/usr/bin/env python3
"""
Cek artikel unused per website brand untuk konten FB.
Fetch semua artikel live dari WP masing-masing brand, bandingkan dengan history FB,
output daftar artikel yang BELUM pernah dipakai (biar konten FB selalu fresh & unik).
"""
import base64, json, os, re, sys
import urllib.request, urllib.error

WS = "/home/mantapman/.hermes/profiles/atun/workspace"

# (nama akun FB, domain, app password, history file atau None)
SITES = [
    ("StudioSoft",  "studiosoft.id",        "q26r RePo BVy6 pwU2 F3z7 ouyl", "studiosoft_fb_history.json"),
    ("DAS Bengkel", "dasindonesia.com",     "VzXR 72KF NJWn XxHI MhJN B9Hs", "post_das_fb_history.json"),
    ("TS Law",      "tslaw.id",             "EFKm EYGx VQCP Y9go ncPr uM2Y", "tslaw_fb_history.json"),
    ("LEIT",        "leitsurabaya.com",     "zibd dLIV xY8x onP9 39qL hiNr", None),
    ("DMark",       "dmark.id",             "fMqR O6jE Tj7t nvqh AMjv PP1V", "post_dmark_fb_history.json"),
    ("Apotek Arlan","apotekpamekasan.com",  "Rab8 qmxV gJ1k yDY3 9ske utCz", None),
    ("RSIA Kendangsari", "rsia.kendangsari.com", "INJ6 7ag4 iouR Fqkm 4alp Dkng", None),
    ("SSC",         "surabaya-skincentre.com", "r4bI jsIF CsAn uTIz SlFa TnJz", None),
]


def fetch_posts(domain, app_pass):
    """Ambil semua post publish dari WP REST API."""
    base = f"https://{domain}/wp-json/wp/v2/posts"
    auth = "Basic " + base64.b64encode(f"bambangbot:{app_pass}".encode()).decode()
    posts = []
    page = 1
    while True:
        req = urllib.request.Request(f"{base}?per_page=50&page={page}&status=publish&_fields=id,title,link,date",
                                     headers={"Authorization": auth, "User-Agent": "Mozilla/5.0"})
        try:
            with urllib.request.urlopen(req, timeout=25) as r:
                batch = json.loads(r.read())
        except urllib.error.HTTPError as e:
            if e.code == 400:  # halaman habis
                break
            return None, f"HTTP {e.code}"
        except Exception as e:
            return None, str(e)[:100]
        posts += batch
        if len(batch) < 50:
            break
        page += 1
    return posts, None


def load_used_urls(history_file):
    """Ambil semua URL artikel yang pernah dipakai dari history FB."""
    used = set()
    if not history_file:
        return used
    path = os.path.join(WS, history_file)
    if not os.path.exists(path):
        return used
    try:
        with open(path) as f:
            d = json.load(f)
    except Exception:
        return used

    raw = json.dumps(d, ensure_ascii=False)
    # ambil semua link http(s) dari history
    for m in re.findall(r'https?://[^\s"\'\\,)\]}]+', raw):
        url = m.rstrip('.,;')
        used.add(url.split('?')[0].rstrip('/'))
    return used


def main():
    report = []
    for name, domain, app_pass, hist in SITES:
        posts, err = fetch_posts(domain, app_pass)
        if err:
            report.append(f"\n## {name} ({domain}) — ⚠️ GAGAL FETCH: {err}")
            continue
        used = load_used_urls(hist)
        unused = []
        for p in posts:
            link = (p.get("link") or "").split("?")[0].rstrip("/")
            if link not in used:
                unused.append((p.get("date", "")[:10], p.get("title", {}).get("rendered", "?"), link))
        # urut: artikel paling baru dulu
        unused.sort(reverse=True)
        report.append(f"\n## {name} ({domain})")
        report.append(f"- Total artikel live: {len(posts)} | Sudah dipakai: {len(posts) - len(unused)} | **Belum dipakai: {len(unused)}**")
        if unused:
            report.append("")
            for date, title, link in unused[:25]:
                t = re.sub(r'<[^>]+>', '', title)
                report.append(f"  - [{date}] {t}\n    {link}")
            if len(unused) > 25:
                report.append(f"  ...dan {len(unused) - 25} artikel lainnya")
        else:
            report.append("  (semua artikel sudah pernah dipakai)")

    out = "\n".join(report)
    outpath = os.path.join(WS, "daftar_artikel_fb_unused.md")
    with open(outpath, "w") as f:
        f.write("# Daftar Artikel FB — Belum Dipakai (untuk konten FB)\n")
        f.write("Dibuat: 4 Agustus 2026. Dipakai sebagai sumber konten FB: tiap posting FB yang bukan series/carousel wajib ambil artikel dari sini (caption minimal 3 paragraf + link artikel + hashtags sesuai topik).\n")
        f.write(out)
    print(out)


if __name__ == "__main__":
    main()
