#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Klasifikasi caption post Threads yang SUCCESS dalam 30 hari -> bauran konten."""
import json, sys, collections, re, datetime

path = sys.argv[1] if len(sys.argv) > 1 else "/tmp/repliz_full_20261004.json"
docs = json.load(open(path))
ACC = {
    "6a334e89c5ff4ce3a3225a48": "uky_threads",
    "6a335b9ec5ff4ce3a3225c2a": "studiosoft_threads",
}
which = sys.argv[2] if len(sys.argv) > 2 else "uky_threads"
aid = [k for k, v in ACC.items() if v == which][0]

pola = [
    ("templat_artikel", re.compile(r"kalau kamu bingung soal|baru baca artikel ini|saya baca artikel ini|ini penjelasan .* yang paling", re.I)),
    ("storytelling5", re.compile(r"konteks\s*—|karakter\s*—|konflik\s*—|klimaks\s*—|kesimpulan\s*—", re.I)),
    ("pertanyaan", re.compile(r"menurut (kamu|anda)|setuju|pilih mana|a\.\s|b\.\s|mit atau fakta|diskusi", re.I)),
    ("quote_kartu", re.compile(r"\.(jpg|png)", re.I)),
]
cnt = collections.Counter()
contoh = collections.defaultdict(list)
links = 0
tot = 0
today = datetime.date(2026, 10, 4)
cut = (today - datetime.timedelta(days=30)).isoformat()
for d in docs:
    if (d.get("account") or {}).get("_id") != aid:
        continue
    if d.get("status") != "success":
        continue
    ds = (d.get("scheduleAt") or "")[:10]
    if ds < cut or ds > today.isoformat():
        continue
    desc = d.get("description") or ""
    tot += 1
    if "http" in desc:
        links += 1
    label = "lain"
    for nm, rx in pola:
        if rx.search(desc):
            label = nm
            break
    cnt[label] += 1
    if len(contoh[label]) < 3:
        contoh[label].append(desc[:150].replace("\n", " "))

print("===", which, "| success 30 hari:", tot, "| ber-link:", links)
for k, v in cnt.most_common():
    print(f"  {k:18} {v:3}  ({v*100//max(tot,1)}%)")
    for c in contoh[k]:
        print("       •", c)
