#!/usr/bin/env python3
"""Data untuk rencana FB + LinkedIn:
1) field 'additional' akun FB (untuk cari URL halaman publik)
2) daftar link yang SUDAH dipakai per akun FB & LinkedIn (dari semua jadwal)
3) 40 artikel terbaru per domain klien (semua link, untuk dipilih yang fresh)
"""
import json, re, subprocess, time

UA = "Mozilla/5.0 (X11; Linux x86_64) Chrome/124"
accs = json.load(open("/tmp/reach_accs.json"))
sch = json.load(open("/tmp/reach_schedules.json"))

print("### field additional akun FB/LinkedIn")
for a in accs:
    if (a.get("type") or "").lower() in ("facebook", "linkedin"):
        print(f"  {a.get('type'):9s} {a['name'][:28]:28s} {json.dumps(a.get('additional'), ensure_ascii=False)[:220]}")

print("\n### link sudah dipakai per akun FB/LinkedIn")
used = {}
for a in accs:
    if (a.get("type") or "").lower() not in ("facebook", "linkedin"):
        continue
    urls = set()
    for s in sch:
        if s.get("accountId") == a["_id"]:
            t = (s.get("description") or "") + " " + (s.get("title") or "")
            for u in re.findall(r"https?://\S+", t):
                urls.add(u.rstrip(".,)").lower().replace("www.", ""))
    used[a["_id"]] = {"nama": a["name"], "platform": a["type"], "urls": sorted(urls)}
    print(f"  {a['type']:9s} {a['name'][:26]:26s} {len(urls):3d} link dipakai")
json.dump(used, open("/tmp/used_fbli.json", "w"), ensure_ascii=False, indent=1)

DOMAIN = {
    "studiosoft.id": "https://studiosoft.id",
    "tslaw.id": "https://www.tslaw.id",
    "theskincodeclinic.com": "https://www.theskincodeclinic.com",
    "dasindonesia.com": "https://dasindonesia.com",
    "everybeofficial.com": "https://www.everybeofficial.com",
}


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 ""


print("\n### 40 artikel terbaru per domain")
semua = {}
for nama, base in DOMAIN.items():
    url = f"{base}/wp-json/wp/v2/posts?per_page=40&_fields=date,link,title&cb={int(time.time())}"
    txt = jina(url)
    m = re.search(r"\[\{.*\}\]", txt, re.S)
    arr = []
    if m:
        try:
            arr = json.loads(m.group(0))
        except Exception:
            arr = []
    hasil = [{"date": (x.get("date") or "")[:10],
              "title": re.sub(r"<[^>]+>", "", (x.get("title") or {}).get("rendered", "")),
              "link": x.get("link", "")} for x in arr]
    semua[nama] = hasil
    print(f"  {nama:26s} {len(hasil)} artikel")
json.dump(semua, open("/tmp/artikel_40_domain.json", "w"), ensure_ascii=False, indent=1)
