#!/usr/bin/env python3
"""Cek akhir: (1) link ada di web (WP REST by slug), (2) link 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"
MAP = {"ukyhandoko": "uky", "studiosoft.id": "studiosoft", "tslaw_firm": "tslaw",
       "theskincode_clinic": "tsc", "das_indonesia": "das"}
items = json.load(open("/home/mantapman/.hermes/profiles/atun/workspace/usulan_caption_20260930.json"))


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


# daftar "sudah dipakai" + tambahkan everybe dari dump jadwal
used = {k: [norm(x) for x in v] for k, v in json.load(open("/tmp/threads_used_all.json")).items()}
sch = json.load(open("/tmp/reach_schedules.json"))
ev = []
for s in sch:
    if s.get("accountId") == "6a44ed1920e4f4f195d8ecf7":
        for u in re.findall(r"https?://\S+", (s.get("description") or "") + " " + (s.get("title") or "")):
            ev.append(norm(u.rstrip(".,)")))
used["everybe"] = ev


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:
    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())}"
    txt = jina(api)
    m = re.search(r"\[\{.*?\}\]", txt, re.S)
    ada = bool(m)
    judul = ""
    if ada:
        try:
            judul = re.sub(r"<[^>]+>", "", json.loads(m.group(0))[0]["title"]["rendered"])
        except Exception:
            judul = ""
    kunci = MAP.get(it["akun"], "everybe")
    fresh = norm(it["link"]) not in used.get(kunci, [])
    tanda = "✅" if (ada and fresh) else "❌"
    if not (ada and fresh):
        gagal += 1
    print(f"{tanda} ada={'ya' if ada else 'TIDAK'} fresh={'ya' if fresh else 'SUDAH DIPAKAI'} "
          f"| {it['akun']:20s} {len(it['caption']):4d} char | {judul[:60]}")
    print(f"     {it['link']}")
print("SEMUA LINK ADA + FRESH" if gagal == 0 else f"{gagal} link bermasalah")
