#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Audit hc64 (13 Okt 2026 02:00 WIB): dump jadwal Repliz + artikel baru WP + matriks jejak T/LI/FB."""
import json, os, re, sys, subprocess
from datetime import datetime, timezone, timedelta

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
sys.path.insert(0, WS)
import repliz_openssl_transport
repliz_openssl_transport.install(verbose=False)
from repliz_client import ReplizClient, ACC

c = ReplizClient()
WIB = timezone(timedelta(hours=7))

def dump():
    docs, page = [], 1
    while True:
        d = c.get("/public/schedule?page=%d&limit=100" % page)
        docs.extend(d.get("docs", []))
        if page >= (d.get("totalPages") or 1):
            break
        page += 1
    return docs

docs = dump()
print("TOTAL docs:", len(docs))
json.dump(docs, open("/tmp/repliz_dump_hc64.json", "w"), ensure_ascii=False)

ACC_MAP = {
    "THREADS": ACC.STUDIOSOFT_THREADS,
    "LINKEDIN": ACC.STUDIOSOFT_LINKEDIN,
    "FB": ACC.STUDIOSOFT_FB,
    "IG": ACC.STUDIOSOFT_IG,
}
URLRE = re.compile(r"https?://[^\s\"'<>)\]]*studiosoft\.id[^\s\"'<>)\]]*")

print("\n=== ARTIKEL WP 30 TERBARU (studiosoft.id) ===")
try:
    r = subprocess.run(["curl", "-4", "-s", "--http1.1", "--max-time", "150",
                        "-A", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)",
                        "https://studiosoft.id/wp-json/wp/v2/posts?per_page=30&_fields=date,slug,title&cb=%d" % int(datetime.now().timestamp())],
                       capture_output=True, text=True)
    posts = json.loads(r.stdout)
    json.dump(posts, open("/tmp/ss_posts_hc64.json", "w"), ensure_ascii=False)
    for p in posts[:30]:
        print("  %s | %s | %s" % (p["date"], p["slug"], (p.get("title") or {}).get("rendered", "")[:60]))
    print("  total posts:", len(posts))
except Exception as e:
    print("  GAGAL WP REST:", e, "| stdout head:", r.stdout[:200] if 'r' in dir() else "")

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

HC = ["7-strategi-digital-marketing-rumah-sakit-untuk-menambah-pasien-setiap-bulan",
      "10-channel-digital-marketing-rumah-sakit-yang-wajib-dikelola-di-era-online",
      "strategi-seo-terbaik-untuk-klinik-kecantikan-di-surabaya-tingkatkan-pasien-lewat-google",
      "tips-seo-digital-marketing-surabaya-optimasi-local-untuk-klinik-dan-bengkel-lokal",
      "7-aplikasi-mental-health-anak-usia-4-10-tahun-yang-harus-dicoba-orang-tua",
      "pembuatan-website-rumah-sakit",
      "jasa-digital-marketing-rs",
      "jasa-digital-marketing-klinik",
      "seo-rumah-sakit",
      "digital-marketing-rumah-sakit-indikator",
      "panduan-seo-klinik-rumah-sakit",
      "rs-klinik-digital-marketing-2026",
      "google-business-profile-klinik",
      "9-contoh-konten-digital-marketing-rumah-sakit-yang-edukatif-dan-tetap-etis",
      "cara-klinik-kecantikan-di-surabaya-bisa-ditemukan-lebih-cepat-di-google"]

for name, aid in ACC_MAP.items():
    print("\n===== %s (%s) =====" % (name, aid))
    rows = [d for d in docs if d.get("accountId") == aid]
    up = [d for d in rows if (d.get("status") or "").lower() in ("pending", "scheduled", "draft")]
    up.sort(key=lambda d: d.get("scheduleAt") or "")
    print("  %d total, %d upcoming" % (len(rows), len(up)))
    if name in ("THREADS", "LINKEDIN", "FB"):
        for d in up:
            when = (d.get("scheduleAt") or "")
            sl = set()
            for s in art_slugs(d):
                sl.add(s)
            print("   %s | %-6s %-8s | %s | %s" % (when[:19], d.get("type"), d.get("status"),
                                                   (d.get("title") or "")[:44], ",".join(sorted(sl))[:70]))

# matriks jejak HC
lastsucc = {"THREADS": {}, "LINKEDIN": {}, "FB": {}}
upc = {"THREADS": {}, "LINKEDIN": {}, "FB": {}}
AID2 = {ACC.STUDIOSOFT_THREADS: "THREADS", ACC.STUDIOSOFT_LINKEDIN: "LINKEDIN", ACC.STUDIOSOFT_FB: "FB"}
for d in docs:
    pl = AID2.get(d.get("accountId"))
    if not pl:
        continue
    st = (d.get("status") or "").lower()
    when = d.get("scheduleAt") or ""
    for s in art_slugs(d):
        if st == "success" and when > lastsucc[pl].get(s, ""):
            lastsucc[pl][s] = when
        if st in ("pending", "scheduled", "draft"):
            upc[pl].setdefault(s, []).append(when[:16])

print("\n=== MATRIKS ARTIKEL HC HIDUP (jejak TERAKHIR SUKSES + jadwal mendatang) ===")
for s in HC:
    print("  %-62s" % s[:62])
    for pl in ("THREADS", "LINKEDIN", "FB"):
        print("     %-9s succ=%-20s up=%s" % (pl, lastsucc[pl].get(s, "BELUM PERNAH"),
                                              (sorted(upc[pl].get(s, []))[:3] or "-")))
