#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""verif_fb_story_reel.py — audit story & reel baru di Facebook StudioSoft (topic awalan 'Story FB'/'Reel FB')."""
import re
from datetime import datetime, timedelta, timezone

from repliz_client import get_client

WIB = timezone(timedelta(hours=7))
ACC = "6a334952c5ff4ce3a3225941"
PREFIX = ("Story FB StudioSoft harian", "Reel FB StudioSoft harian")

c = get_client()
rows, page = [], 1
while True:
    r = c.get_schedules(page=page, limit=100)
    docs = r.get("docs") or r.get("data") or []
    if not docs:
        break
    for d in docs:
        if d.get("accountId") == ACC and (d.get("topic") or "") in PREFIX:
            rows.append(d)
    if len(docs) < 100:
        break
    page += 1

rows.sort(key=lambda x: x["scheduleAt"])
masalah = []
for label, tipe in (("STORY", "story"), ("REEL", "reel")):
    sub = [d for d in rows if d.get("type") == tipe]
    if not sub:
        continue
    jam = {}
    for d in sub:
        t = datetime.strptime(d["scheduleAt"], "%Y-%m-%dT%H:%M:%S.%fZ").replace(
            tzinfo=timezone.utc).astimezone(WIB)
        jam.setdefault(t.strftime("%d %b"), []).append(t.strftime("%H:%M"))
        teks = d.get("description") or ""
        err = []
        if d.get("status") != "pending":
            err.append(f"status={d.get('status')}")
        if len(d.get("replies") or []):
            err.append("replies tidak kosong")
        if len(d.get("medias") or []) != 1:
            err.append(f"media {len(d.get('medias') or [])}")
        if tipe == "story" and teks.strip():
            err.append("story ada caption (harus kosong)")
        if tipe == "reel":
            if not (100 <= len(teks) <= 2200):
                err.append(f"caption {len(teks)}")
            if not re.search(r"komentar", teks[-160:], re.I):
                err.append("tanpa ajakan komentar")
            bad = [x for x in re.findall(r"#(\w+)", teks) if x != x.lower()]
            if bad:
                err.append(f"hashtag kapital {bad}")
        cjk = [ch for ch in teks if "\u3000" <= ch <= "\u9fff" or "\uac00" <= ch <= "\ud7af"]
        if cjk:
            err.append(f"CJK {cjk[:3]}")
        if err:
            masalah.append((tipe, t, d.get("title"), err))
    print(f"== {label}: {len(sub)} jadwal | {min(jam)} s/d {max(jam)} | jam terpakai: "
          f"{sorted({j for v in jam.values() for j in v})}")
    print("   sebaran:", ", ".join(f"{k} {'/'.join(v)}" for k, v in list(jam.items())[:6]), "…")

print(f"\nMASALAH: {len(masalah)}")
for m in masalah:
    print("  ⚠️", m[0], m[1].strftime("%d %b %H:%M"), (m[2] or "")[:48], m[3])
