#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Pilih kandidat artikel untuk run hc62 (Threads carousel / LinkedIn / Facebook)."""
import json, re, sys, subprocess
from datetime import datetime, timezone, timedelta

WIB = timezone(timedelta(hours=7))
docs = json.load(open("/tmp/repliz_dump_hc62.json"))

ACC_T = "6a335b9ec5ff4ce3a3225c2a"
ACC_LI = "6a334c49c5ff4ce3a32259c9"
ACC_FB = "6a334952c5ff4ce3a3225941"

URLRE = re.compile(r"https?://[^\s\"'<>)\]]*studiosoft\.id/[^\s\"'<>)\]]*")


def slug_of(u):
    u = u.split("?")[0].split("#")[0].rstrip("/")
    return u.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" in u:
                continue
            out.add(slug_of(u))
    for f in ("description", "title", "topic"):
        for u in URLRE.findall(d.get(f) or ""):
            if "openclaw-img" in u:
                continue
            out.add(slug_of(u))
    return out


def trace(acc, want_status=None):
    """map slug -> list of (scheduleAt, status, type)"""
    t = {}
    for d in docs:
        if d.get("accountId") != acc:
            continue
        st = (d.get("status") or "").lower()
        if want_status and st not in want_status:
            continue
        when = d.get("scheduleAt") or ""
        for s in art_slugs(d):
            t.setdefault(s, []).append((when, st, d.get("type")))
    return t


now = datetime(2026, 10, 10, 19, 0, tzinfo=timezone.utc)
UP = ("pending", "scheduled", "draft")

for label, acc in (("THREADS", ACC_T), ("LINKEDIN", ACC_LI), ("FB", ACC_FB)):
    t = trace(acc)
    up = trace(acc, want_status=UP)
    print("\n########## %s ##########" % label)
    # upcoming slugs
    print("-- upcoming slugs (pending/scheduled/draft), sorted by time --")
    rows = []
    for s, lst in up.items():
        for w, st, ty in lst:
            rows.append((w, s, st, ty))
    rows.sort()
    for w, s, st, ty in rows:
        print("   %s %-9s %-8s %s" % (w[:16], st, ty, s))
