#!/usr/bin/env python3
"""Verify hc46: fetch ulang dari API — medias (urutan), replies, jadwal anak, media jalur internet, jam WIB."""
import json, os, subprocess, sys
from datetime import datetime, timedelta, timezone

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

c = ReplizClient()
ALBUM = "6ab574fd0723d7da88c3f9f2"
IDS = {
    "threads_album": ALBUM,
    "linkedin": "6ab574fd0723d7da88c3fa16",
    "facebook": "6ab574fe0723d7da88c3fa21",
}
EXPECT = ["ss_hc46_klinikcan_01_cover.jpg", "ss_hc46_klinikcan_02_lokal.jpg",
          "ss_hc46_klinikcan_03_website.jpg", "ss_hc46_klinikcan_04_reputasi.jpg",
          "ss_hc46_klinikcan_05_cta.jpg"]


def wib(s):
    if not s:
        return "-"
    try:
        return (datetime.fromisoformat(s.replace("Z", "+00:00")) + timedelta(hours=7)).strftime("%d %b %Y %H:%M WIB")
    except Exception:
        return s


def norm_replies(v):
    """Repliz kadang serialisasi ObjectId jadi dict {'0':'6','1':'a',...,'status':'pending'}."""
    out = []
    for r in v or []:
        if isinstance(r, dict):
            ks = [k for k in r.keys() if str(k).isdigit()]
            out.append("".join(str(r[k]) for k in sorted(ks, key=lambda x: int(x))))
        else:
            out.append(str(r))
    return out


ok = True
for name, sid in IDS.items():
    try:
        d = c.get("/public/schedule/%s" % sid)
    except Exception as e:
        print("  %s: FETCH GAGAL %s" % (name, e))
        ok = False
        continue
    doc = d.get("doc") or d.get("data") or d
    print("\n### %s (%s)" % (name, sid))
    print("  status=%s type=%s at=%s (%s)" % (doc.get("status"), doc.get("type"),
                                              doc.get("scheduleAt"), wib(doc.get("scheduleAt"))))
    print("  title=%r" % (doc.get("title") or "")[:70])
    meds = [os.path.basename((m.get("url") or "").split("?")[0]) for m in (doc.get("medias") or [])]
    for i, b in enumerate(meds, 1):
        print("   media %d: %s" % (i, b))
    print("  replies=%s" % (norm_replies(doc.get("replies")) or "[]"))
    desc = doc.get("description") or ""
    print("  desc_len=%d tail=%s" % (len(desc), desc[-100:].replace("\n", " | ")))
    if name == "threads_album":
        if meds != EXPECT:
            print("  \u274c URUTAN MEDIA TIDAK SESUAI")
            ok = False
        else:
            print("  \u2705 urutan media 1-5 benar")
        if doc.get("status") != "pending":
            print("  \u274c status bukan pending")
            ok = False
    if name in ("linkedin", "facebook"):
        if meds:
            print("  \u274c ada media (aturan: tanpa gambar)")
            ok = False
        else:
            print("  \u2705 tanpa media")
        if norm_replies(doc.get("replies")):
            print("  \u274c ada replies (FB wajib kosong)")
            ok = False
        else:
            print("  \u2705 replies kosong")

print("\n### dump jadwal: cari reply anak album hc46 + jejak media:")
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
print("  dump %d docs" % len(docs))
nchild = 0
for s in docs:
    if ALBUM in norm_replies(s.get("replies")):
        nchild += 1
        print("   ANAK %s | %s | %s | %s | desc_tail=%s" % (
            s.get("accountId"), s.get("status"), s.get("scheduleAt"), s.get("type"),
            (s.get("description") or "")[-70:].replace("\n", " | ")))
print("  reply anak album: %d %s" % (nchild, "\u2705" if nchild == 2 else "\u274c harusnya 2"))
if nchild != 2:
    ok = False
for s in docs:
    for m in (s.get("medias") or []):
        b = os.path.basename((m.get("url") or "").split("?")[0])
        if b.startswith("ss_hc46_klinikcan_"):
            print("   MEDIA %s | %s | %s | %s" % (s.get("accountId"), s.get("status"),
                                                  s.get("scheduleAt"), b))
            break

print("\n### media jalur internet (kedua ingress) + link artikel:")
for f in EXPECT:
    u = "https://mantapserver.tail3947bb.ts.net/openclaw-img/" + f
    codes = []
    for ip in ("103.84.155.153", "103.84.155.217"):
        r = subprocess.run(["curl", "-s", "-o", "/dev/null", "-w", "%{http_code}", "--max-time", "60",
                            "--resolve", "mantapserver.tail3947bb.ts.net:443:%s" % ip, u],
                           capture_output=True, text=True)
        codes.append(r.stdout.strip())
    print("  %s -> %s %s" % (f, codes, "\u2705" if codes == ["200", "200"] else "\u274c"))
    if codes != ["200", "200"]:
        ok = False

print("\nstate:", json.loads(open(WS + "/studiosoft_healthcare_state.json").read()))
print("\nHASIL VERIFIKASI:", "SEMUA OK" if ok else "ADA MASALAH")
sys.exit(0 if ok else 1)
