#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Cek semua jadwal Repliz untuk akun Soto Semarang Pak Otto (audit STOP 24 Sep 2026)."""
import json
import os
import sys
from datetime import datetime, timezone, timedelta

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from repliz_client import ReplizClient

WIB = timezone(timedelta(hours=7))

OTTO = {
    "6a86d84b62caae1e04fff12c": "SOTO_THREADS (@sotosemarang.pakotto)",
    "6a86d6e962caae1e04ffedaa": "SOTO_IG (@sotosemarangpakotto)",
    "6a86d70362caae1e04ffedef": "SOTO_TIKTOK (sotosemarang.pakotto)",
    "6a8f9df162caae1e040754d8": "OTTO_FB (FB Warung Pak Otto)",
}


def main():
    c = ReplizClient()
    rows = []
    page = 1
    while True:
        r = c.get_schedules(page=page, limit=50)
        data = r.get("data") if isinstance(r, dict) else None
        if isinstance(data, dict):
            items = data.get("docs") or data.get("items") or data.get("data") or []
        elif isinstance(data, list):
            items = data
        else:
            items = r.get("docs") or r.get("items") or []
        if not items:
            break
        rows.extend(items)
        if len(items) < 50:
            break
        page += 1

    print(f"total jadwal terbaca: {len(rows)}")
    now = datetime.now(timezone.utc)
    hit = []
    for it in rows:
        acc = it.get("accountId") or it.get("account") or ""
        if isinstance(acc, dict):
            acc = acc.get("_id") or acc.get("id") or ""
        if acc not in OTTO:
            continue
        sched = it.get("scheduleAt") or it.get("schedule_at") or it.get("scheduledAt") or ""
        st = (it.get("status") or "").lower()
        try:
            dt = datetime.fromisoformat(str(sched).replace("Z", "+00:00"))
        except Exception:
            dt = None
        future = bool(dt and dt > now)
        hit.append({
            "id": it.get("_id") or it.get("id"),
            "akun": OTTO[acc],
            "status": st,
            "jadwal_utc": sched,
            "jadwal_wib": dt.astimezone(WIB).strftime("%Y-%m-%d %H:%M WIB") if dt else sched,
            "future": future,
            "desc": (it.get("description") or "")[:120].replace("\n", " "),
        })

    hit.sort(key=lambda x: x["jadwal_utc"])
    for h in hit:
        print(f"[{h['status']}] {h['jadwal_wib']} | {h['akun']} | id={h['id']} | future={h['future']}")
        print(f"     {h['desc']}")
    print(f"\njumlah jadwal Otto: {len(hit)}  |  masih future: {sum(1 for h in hit if h['future'])}")


if __name__ == "__main__":
    main()
