#!/usr/bin/env python3
"""Ambil artikel fresh (belum pernah dipakai di Threads) per akun."""
import json, sys, subprocess, urllib.parse

USED = json.load(open('/tmp/threads_used_all.json'))
SITES = {
    'studiosoft': ('https://studiosoft.id', 'https://studiosoft.id/wp-json/wp/v2/posts?per_page=60&_fields=link,title,date,excerpt'),
    'uky': ('https://studiosoft.id', 'https://studiosoft.id/wp-json/wp/v2/posts?per_page=60&_fields=link,title,date,excerpt'),
    'tslaw': ('https://www.tslaw.id', 'https://www.tslaw.id/wp-json/wp/v2/posts?per_page=60&_fields=link,title,date,excerpt'),
    'tsc': ('https://www.theskincodeclinic.com', 'https://www.theskincodeclinic.com/wp-json/wp/v2/posts?per_page=60&_fields=link,title,date,excerpt'),
    'das': ('https://dasindonesia.com', 'https://dasindonesia.com/wp-json/wp/v2/posts?per_page=60&_fields=link,title,date,excerpt'),
}


def norm(u):
    u = u.strip().rstrip('/').lower()
    for p in ('https://', 'http://', 'www.'):
        u = u.replace(p, '')
    return u


def main():
    acc = sys.argv[1]
    domain, api = SITES[acc]
    out = subprocess.run(['curl', '-sS', '-m', '60', api], capture_output=True, text=True)
    posts = json.loads(out.stdout)
    used = USED.get(acc, {})
    usedset = set()
    if isinstance(used, dict):
        for it in used.get('urls', []) if 'urls' in used else []:
            usedset.add(norm(it if isinstance(it, str) else it.get('url', '')))
    if isinstance(used, list):
        for it in used:
            usedset.add(norm(it if isinstance(it, str) else it.get('url', '')))
    # fallback: any list of strings
    print(f"== {acc}: {len(posts)} artikel di API, {len(usedset)} URL terpakai", file=sys.stderr)
    fresh = []
    for p in posts:
        link = p['link']
        if norm(link) in usedset:
            continue
        fresh.append(p)
    print(f"-- fresh {len(fresh)}")
    for p in fresh:
        title = p['title']['rendered'].replace('&nbsp;', ' ')
        print(f"{p['date'][:10]}  {p['link']}\n            {title}")


if __name__ == '__main__':
    main()
