#!/usr/bin/env python3
"""
Scan teks CJK (China/Jepang/Korea) yang nyasar ke caption/title jadwal Repliz.
Aturan Bos 27 Sep 2026: TIDAK BOLEH ada teks China di konten apa pun.

Pemakaian:
    python3 cek_teks_china.py fetch     # ambil semua jadwal → /tmp/repliz_all_sched.json
    python3 cek_teks_china.py           # scan dump, cetak temuan CJK

Exit code 1 kalau ada temuan di jadwal pending/future (yang masih bisa tayang).
"""
import json
import os
import re
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
DUMP = "/tmp/repliz_all_sched.json"

CJK = re.compile(r"[\u3000-\u303f\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff00-\uffef]")


def norm(x):
    """dict → semua string di dalamnya, biar caption ikut kebaca."""
    out = []
    if isinstance(x, str):
        out.append(x)
    elif isinstance(x, dict):
        for v in x.values():
            out.extend(norm(v))
    elif isinstance(x, list):
        for v in x:
            out.extend(norm(v))
    return out


def fetch():
    sys.path.insert(0, HERE)
    from repliz_client import get_client
    c = get_client()
    all_sched, page = [], 1
    while True:
        r = c.get_schedules(page=page, limit=50)
        docs = r.get("docs") or r.get("data") or []
        if not docs:
            break
        all_sched.extend(docs)
        if not r.get("hasNextPage") and len(docs) < 50:
            break
        page += 1
    with open(DUMP, "w") as f:
        json.dump(all_sched, f)
    print(f"dump: {len(all_sched)} jadwal → {DUMP}")


def scan(path=DUMP):
    docs = json.load(open(path))
    hits = []
    for d in docs:
        texts = norm({k: v for k, v in d.items() if k != "account"})
        for t in texts:
            m = CJK.findall(t)
            if m:
                hits.append({
                    "id": d.get("_id"),
                    "account": (d.get("account") or {}).get("name"),
                    "accountId": d.get("accountId") or (d.get("account") or {}).get("_id"),
                    "status": d.get("status"),
                    "scheduleAt": d.get("scheduleAt"),
                    "chars": "".join(sorted(set(m))),
                    "snippet": re.sub(r"\s+", " ", t)[:160],
                })
                break
    order = {"pending": 0, "draft": 1}
    hits.sort(key=lambda h: (order.get(h["status"], 2), h["scheduleAt"] or ""))
    print(f"Temuan CJK: {len(hits)} jadwal (dari {len(docs)} discan)")
    for h in hits:
        print(f"  [{h['status']}] {h['scheduleAt']} {h['account']} {h['id']}")
        print(f"      chars={h['chars']}")
        print(f"      {h['snippet']}")
    json.dump(hits, open("/tmp/teks_china_hits.json", "w"), ensure_ascii=False, indent=1)
    live = [h for h in hits if (h["status"] or "") in ("pending", "draft")]
    return 1 if live else 0


if __name__ == "__main__":
    if len(sys.argv) > 1 and sys.argv[1] == "fetch":
        fetch()
    sys.exit(scan(sys.argv[2] if len(sys.argv) > 2 else DUMP))
