#!/usr/bin/env python3
"""Detail + verifikasi CAROUSEL TS Law: media 200 dua ingress, caption, link, CTA, hashtag, story mirror."""
import sys, json, re, subprocess
from datetime import datetime, timezone, timedelta
from concurrent.futures import ThreadPoolExecutor

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

WIB = timezone(timedelta(hours=7))
INDEKS = ["103.84.155.153", "103.84.155.217"]
HOST = "mantapserver.tail3947bb.ts.net"

c = ReplizClient()

TARGET = {
    "ig": ACC.TSLAW_IG,
    "fb": ACC.TSLAW_FB,
    "threads": ACC.TSLAW_THREADS,
}


def ambil_semua():
    rows, page = [], 1
    while True:
        r = c.get(f"/public/schedule?page={page}&limit=100")
        d = r.get("docs", [])
        if not d:
            break
        rows += d
        if page >= r.get("totalPages", 1):
            break
        page += 1
    return rows


def cek_url(ip, url):
    u = url.replace(f"https://{HOST}", f"https://{HOST}")
    cmd = ["curl", "-sk", "-o", "/dev/null", "-w", "%{http_code}", "--max-time", "25",
           "--resolve", f"{HOST}:443:{ip}", u]
    try:
        return subprocess.run(cmd, capture_output=True, text=True, timeout=40).stdout.strip()
    except Exception as e:
        return f"ERR {e}"


rows = ambil_semua()
all_urls = set()
detail = []
for ch, aid in TARGET.items():
    for d in rows:
        if d.get("accountId") != aid or str(d.get("type", "")).lower() != "album":
            continue
        if d.get("status") != "pending":
            continue
        sat = datetime.fromisoformat(d["scheduleAt"].replace("Z", "+00:00")).astimezone(WIB)
        urls = [m.get("url") for m in (d.get("medias") or [])]
        all_urls.update(urls)
        desc = d.get("description") or ""
        detail.append(dict(ch=ch, id=d.get("_id"), sat=sat.strftime("%Y-%m-%d %H:%M"),
                           title=d.get("title"), n=len(urls), desc=desc, urls=urls,
                           replies=d.get("replies")))

print(f"jadwal carousel PENDING: {len(detail)}  | url unik: {len(all_urls)}")
print("\n--- CAPTION / ISI ---")
for x in sorted(detail, key=lambda z: (z["sat"], z["ch"])):
    tags = re.findall(r"#(\w+)", x["desc"])
    besar = [t for t in tags if t != t.lower()]
    cta = re.findall(r"komentar|diskusi|pendapat|tulis di|share|pengalaman|menurut anda|setuju", x["desc"], re.I)
    link = re.findall(r"https?://\S+", x["desc"])
    cjk = re.findall(r"[\u3000-\u9fff\uac00-\ud7af\uff00-\uffef]", x["desc"])
    print(f"[{x['ch']:7}] {x['sat']} | {x['n']} media | caption {len(x['desc'])} char | "
          f"link {len(link)} | cta={bool(cta)} | hashtag={len(tags)} besar={besar} | CJK={len(cjk)} | replies={len(x['replies'] or [])}")
    print(f"          {x['title']}")
    if link:
        print(f"          link: {link[0]}")

print("\n--- MEDIA HTTP (dua ingress) ---")
tasks = []
with ThreadPoolExecutor(max_workers=8) as ex:
    for u in sorted(all_urls):
        for ip in INDEKS:
            tasks.append((u, ip, ex.submit(cek_url, ip, u)))
    hasil = {}
    for u, ip, f in tasks:
        hasil[(u, ip)] = f.result()

bad = 0
for u in sorted(all_urls):
    codes = [hasil[(u, ip)] for ip in INDEKS]
    ok = all(x == "200" for x in codes)
    if not ok:
        bad += 1
        print(f"  ❌ {codes} {u}")
print(f"  media OK: {len(all_urls) - bad}/{len(all_urls)} (gagal: {bad})")

json.dump({"urls": sorted(all_urls), "detail": [{k: v for k, v in x.items() if k != 'urls'} for x in detail]},
          open("/tmp/cek_carousel_tslaw.json", "w"), indent=2, ensure_ascii=False)
