#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Cari artikel FRESH (belum dipakai di Threads) untuk tiap akun."""
import json, subprocess, sys

USED = json.load(open("/tmp/threads_used_all.json"))


def norm(u):
    return (u or "").rstrip("/").lower()


def fetch(base):
    out = []
    for page in range(1, 8):
        url = f"{base}/wp-json/wp/v2/posts?per_page=100&page={page}&_fields=link,title,date"
        p = subprocess.run(["curl", "-4", "-s", "-m", "40", url], capture_output=True, text=True)
        try:
            data = json.loads(p.stdout)
        except Exception:
            break
        if not isinstance(data, list) or not data:
            break
        out += data
        if len(data) < 100:
            break
    return out


CONF = {
    "studiosoft": ("https://studiosoft.id", ["studiosoft", "uky"]),
    "tsc": ("https://www.theskincodeclinic.com", ["tsc"]),
    "das": ("https://dasindonesia.com", ["das"]),
    "tslaw": ("https://www.tslaw.id", ["tslaw"]),
}

for name, (base, usedkeys) in CONF.items():
    arts = fetch(base)
    used = set()
    for k in usedkeys:
        for u in USED.get(k, []):
            used.add(norm(u))
    print(f"\n===== {name}: {len(arts)} artikel, {len(used)} URL pernah dipakai")
    fresh = []
    for a in arts:
        lk = a.get("link")
        if norm(lk) not in used:
            fresh.append((a.get("date", "")[:10], lk, a.get("title", {}).get("rendered", "")))
    fresh.sort(reverse=True)
    print(f"  FRESH: {len(fresh)}")
    for d, lk, t in fresh[:25]:
        print(f"   {d} | {lk}")
        print(f"        {t[:80]}")
