#!/usr/bin/env python3
"""Verifikasi 12 link caption FB & LinkedIn: ada di web + belum pernah dipakai di akun itu."""
import json, re, subprocess, time
from urllib.parse import urlparse

UA = "Mozilla/5.0 (X11; Linux x86_64) Chrome/124"
ACC = {
    "StudioSoft (Facebook)": "6a334952c5ff4ce3a3225941",
    "Tito Supriyanto Law Firm (Facebook)": "6a3b41d1c5ff4ce3a32753e8",
    "The Skin Code Clinic (Facebook)": "6a3b41ddc5ff4ce3a327542c",
    "StudioSoft (LinkedIn)": "6a334c49c5ff4ce3a32259c9",
    "Uky Yanuhandoko (LinkedIn)": "6a33ca10c5ff4ce3a322705d",
    "The Skin Code Clinic (LinkedIn)": "6a4da7f520e4f4f195e796e1",
}
used = json.load(open("/tmp/used_fbli.json"))
items = json.load(open("/home/mantapman/.hermes/profiles/atun/workspace/usulan_caption_fb_li_20260930.json"))


def norm(u):
    return u.rstrip("/").lower().replace("www.", "")


def jina(url):
    p = subprocess.run(["curl", "-4", "-sL", "--compressed", "--max-time", "80", "-A", UA,
                        f"https://r.jina.ai/{url}"], capture_output=True, text=True, errors="replace")
    return p.stdout or ""


gagal = 0
for it in items:
    aid = ACC[it["akun"]]
    dipakai = set(used.get(aid, {}).get("urls", []))
    u = urlparse(it["link"])
    slug = u.path.strip("/").split("/")[-1]
    api = f"{u.scheme}://{u.netloc}/wp-json/wp/v2/posts?slug={slug}&_fields=date,title&cb={int(time.time())}"
    judul, ada = "", False
    for attempt in range(3):
        txt = jina(api if attempt == 0 else api + str(attempt))
        m = re.search(r"\[\{.*?\}\]", txt, re.S)
        if m:
            try:
                judul = re.sub(r"<[^>]+>", "", json.loads(m.group(0))[0]["title"]["rendered"])
                ada = True
                break
            except Exception:
                pass
        time.sleep(4)
    fresh = norm(it["link"]) not in dipakai
    if not (ada and fresh):
        gagal += 1
    print(f"{'✅' if (ada and fresh) else '❌'} ada={'ya' if ada else 'TIDAK'} fresh={'ya' if fresh else 'SUDAH DIPAKAI'} "
          f"| {it['platform']:8s} {it['akun'][:34]:34s} {len(it['caption']):5d} char | {judul[:52]}")
print("SEMUA LINK FB/LI ADA + FRESH" if gagal == 0 else f"{gagal} link bermasalah")
