#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Pilih artikel HC utk Threads/FB (hc62) + kandidat LinkedIn."""
import json, re
from datetime import datetime, timezone, timedelta

WIB = timezone(timedelta(hours=7))
docs = json.load(open("/tmp/repliz_dump_hc62.json"))
arts = []
for p in (1, 2, 3, 4):
    arts += json.load(open("/tmp/ss_p%d.json" % p))

ACC_T = "6a335b9ec5ff4ce3a3225c2a"
ACC_LI = "6a334c49c5ff4ce3a32259c9"
ACC_FB = "6a334952c5ff4ce3a3225941"
UP = ("pending", "scheduled", "draft")

URLRE = re.compile(r"https?://[^\s\"'<>)\]]*studiosoft\.id/[^\s\"'<>)\]]*")
HCKEY = re.compile(r"rumah-sakit|klinik|kecantikan|kesehatan|mental-health|apotek|dokter|pasien|medis", re.I)


def slug_of(u):
    return u.split("?")[0].split("#")[0].rstrip("/").split("/")[-1].lower()


def art_slugs(d):
    out = set()
    for m in (d.get("medias") or []):
        for u in URLRE.findall(m.get("url") or ""):
            if "openclaw-img" not in u:
                out.add(slug_of(u))
    for f in ("description", "title", "topic"):
        for u in URLRE.findall(d.get(f) or ""):
            if "openclaw-img" not in u:
                out.add(slug_of(u))
    return out


def scan(acc):
    last = {}      # slug -> max scheduleAt (any status)
    upc = {}       # slug -> min scheduleAt upcoming
    for d in docs:
        if d.get("accountId") != acc:
            continue
        st = (d.get("status") or "").lower()
        when = d.get("scheduleAt") or ""
        for s in art_slugs(d):
            if when > last.get(s, ""):
                last[s] = when
            if st in UP:
                if s not in upc or when < upc[s]:
                    upc[s] = when
    return last, upc


lt, ut = scan(ACC_T)
lf, uf = scan(ACC_FB)
ll, ul = scan(ACC_LI)

hc = [a for a in arts if HCKEY.search(a["slug"])]
print("HC articles: %d" % len(hc))
print("\n== HC: jejak Threads terakhir (naik = paling tua) ==")
rows = []
for a in hc:
    s = a["slug"]
    rows.append((lt.get(s, "Belum pernah"), a["date"][:10], s, ut.get(s, "-"), lf.get(s, "Belum pernah"), uf.get(s, "-")))
rows.sort()
for r in rows:
    print("  T.last=%s | art=%s | %-70s | T.up=%s | FB.last=%s | FB.up=%s" % r)

print("\n== Kandidat LinkedIn: artikel TERBARU yang BELUM ada di antrean LI ==")
liup = set(ul.keys())
for a in sorted(arts, key=lambda x: x["date"], reverse=True)[:30]:
    s = a["slug"]
    if s in liup:
        continue
    print("  %s  %s" % (a["date"][:10], s))
