#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Verifikasi jadwal bank konten DAS (@das_indonesia) — baca balik dari API.

Pakai: python3 verif_bank_das_threads.py

Cek per jadwal: status, jam WIB, tipe text, ada balasan anak, caption <=500,
ada ajakan komentar di ekor, hashtag huruf kecil, tanpa mention, tanpa CJK,
dan tidak ada link (bank ini memang tanpa link).
"""
import json, re, sys, datetime
sys.path.insert(0, "/home/mantapman/.hermes/profiles/atun/workspace")
from repliz_client import get_client

AKUN = "6a39e461c5ff4ce3a3233e09"
WIB = datetime.timezone(datetime.timedelta(hours=7))
CTA_RE = re.compile(r"komentar|diskusi|pendapat|tulis di|ceritakan|share|pengalaman|setuju|\?", re.I)
CJK = re.compile(r"[\u3000-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff00-\uffef]")

ids = {x["id"] for x in json.load(open("bank_das_threads_hasil.json")) if x.get("id")}
print(f"id yang harus dicek: {len(ids)}")

c = get_client()
docs, page = [], 1
while True:
    r = c.get(f"/public/schedule?page={page}&limit=100")
    d = r.get("docs") or []
    docs.extend(d)
    if not d or page * 100 >= (r.get("totalDocs") or 0):
        break
    page += 1
mine = [x for x in docs if (x.get("account") or {}).get("_id") == AKUN]
target = [x for x in mine if x.get("_id") in ids]
print(f"ketemu di API: {len(target)} dari {len(ids)}")

masalah_total = 0
for x in sorted(target, key=lambda y: y.get("scheduleAt") or ""):
    t = x.get("scheduleAt") or ""
    jam = datetime.datetime.fromisoformat(t.replace("Z", "+00:00")).astimezone(WIB).strftime("%Y-%m-%d %H:%M")
    d = x.get("description") or ""
    rep = x.get("replies") or []
    m = []
    if x.get("status") != "pending":
        m.append(f"status={x.get('status')}")
    if x.get("type") != "text":
        m.append(f"tipe={x.get('type')}")
    if len(d) > 500:
        m.append(f"len={len(d)}")
    if not rep:
        m.append("tanpa-balasan")
    if not CTA_RE.search(d[-120:]):
        m.append("tanpa-CTA")
    tags = re.findall(r"#(\w+)", d)
    if any(g != g.lower() for g in tags):
        m.append("hashtag-besar")
    if not tags:
        m.append("tanpa-hashtag")
    if re.search(r"@\w+", d):
        m.append("mention")
    if CJK.search(d):
        m.append("CJK")
    if re.search(r"https?://", d):
        m.append("ada-link")
    masalah_total += len(m)
    print(f"  {jam} | {x.get('status'):7} | len={len(d):3} | balasan={len(rep)} | "
          f"topic={x.get('topic')!r} | {'❌ ' + ','.join(m) if m else '✅'}")

print(f"\nselesai — total masalah: {masalah_total}")
sys.exit(1 if masalah_total else 0)
