#!/usr/bin/env python3
"""hc46 audit: dump jadwal Repliz + matriks artikel healthcare x Threads/LI/FB SS + status HTTP tiap artikel."""
import json, re, subprocess, sys, time
WS = "/home/mantapman/.hermes/profiles/atun/workspace"
sys.path.insert(0, WS)
from repliz_client import ACC, ReplizClient

DUMP = "/tmp/repliz_all_20260926.json"

HC = ["data-analytics-rumah-sakit-kebutuhan-pasien", "iklan-facebook-rumah-sakit",
      "google-business-profile-klinik", "social-media-rumah-sakit-efektif",
      "klinik-kecil-butuh-digital-marketing", "panduan-seo-klinik-rumah-sakit",
      "konten-edukasi-kesehatan-kepercayaan-pasien", "website-rumah-sakit-gagal-pasien",
      "strategi-digital-marketing-rumah-sakit", "rs-klinik-digital-marketing-2026",
      "jasa-digital-marketing-klinik",
      "10-channel-digital-marketing-rumah-sakit-yang-wajib-dikelola-di-era-online",
      "9-contoh-konten-digital-marketing-rumah-sakit-yang-edukatif-dan-tetap-etis",
      "strategi-seo-terbaik-untuk-klinik-kecantikan-di-surabaya-tingkatkan-pasien-lewat-google",
      "7-strategi-digital-marketing-rumah-sakit-untuk-menambah-pasien-setiap-bulan",
      "cara-klinik-kecantikan-di-surabaya-bisa-ditemukan-lebih-cepat-di-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"]

print("### 1) status HTTP tiap artikel HC")
alive = []
for s in HC:
    u = "https://studiosoft.id/%s/" % s
    r = subprocess.run(["curl", "-sIL", "--http1.1", "--max-time", "90",
                        "-A", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)", u,
                        "-o", "/dev/null", "-w", "%{http_code}"], capture_output=True, text=True)
    code = (r.stdout or "").strip()
    print("  %s  %s" % (code, s))
    if code == "200":
        alive.append(s)

print("\n### 2) dump jadwal Repliz -> %s" % DUMP)
c = ReplizClient()
docs, page = [], 1
while True:
    last = None
    for i in range(6):
        try:
            d = c.get("/public/schedule?page=%d&limit=100" % page)
            break
        except Exception as e:
            last = e
            time.sleep(3 + 3 * i)
    else:
        raise last
    docs.extend(d.get("docs", []))
    if page >= (d.get("totalPages") or 1):
        break
    page += 1
json.dump(docs, open(DUMP, "w"))
print("  docs:", len(docs))

url_re = re.compile(r"studiosoft\.id/([a-z0-9\-]+)")


def traces(aid, s):
    out = []
    for d in docs:
        if d.get("accountId") != aid:
            continue
        t = " ".join([(d.get("description") or ""), (d.get("title") or "")])
        if s in url_re.findall(t):
            out.append(((d.get("scheduleAt") or "")[:16], d.get("status")))
    return sorted(out)


ACCID = {"T": ACC.STUDIOSOFT_THREADS, "L": ACC.STUDIOSOFT_LINKEDIN, "F": ACC.STUDIOSOFT_FB}
print("\n### 3) matriks (hanya artikel hidup)")
print("%-58s %-26s %-26s %s" % ("SLUG", "THREADS", "LINKEDIN", "FACEBOOK"))
for s in HC:
    tag = "" if s in alive else " [DEAD/404]"
    cells = []
    for k in ("T", "L", "F"):
        tr = traces(ACCID[k], s)
        ok = sum(1 for x in tr if x[1] == "success")
        pend = [x for x in tr if x[1] in ("pending", "scheduled", "draft")]
        err = sum(1 for x in tr if x[1] == "error")
        last = tr[-1][0] if tr else "-"
        if not tr:
            cell = "FREE"
        elif pend:
            cell = "ok%d pend%d(%s)" % (ok, len(pend), pend[0][0])
        else:
            cell = "ok%d err%d last%s" % (ok, err, last)
        cells.append(cell)
    print("%-58s %-26s %-26s %s%s" % (s[:58], cells[0], cells[1], cells[2], tag))

print("\n### 4) jadwal THREADS SS 09:00Z (booked)")
booked = sorted(set((d.get("scheduleAt") or "")[:16] for d in docs
                    if d.get("accountId") == ACC.STUDIOSOFT_THREADS and (d.get("scheduleAt") or "")[11:16] == "02:00"
                    and (d.get("status") or "").lower() in ("pending", "scheduled", "draft")))
for b in booked:
    print("  ", b)
