#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Audit akun Threads DAS (@das_indonesia) — read-only.

Jalankan: python3 audit_das_threads.py

Yang dicek:
  1. Semua jadwal akun DAS Threads (semua status): tipe, media, hashtag, link, jam WIB.
  2. Komentar masuk (GET /public/comment) untuk akun ini.
  3. Ringkasan: bauran, jam, domain link, error.

Follower TIDAK ada di API Repliz — pakai:
  curl -4 -s "https://r.jina.ai/https://www.threads.com/@das_indonesia" | grep followers
"""
import re, sys, json, datetime, collections

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

ACC = "6a39e461c5ff4ce3a3233e09"   # DAS INDONESIA (threads)
WIB = datetime.timezone(datetime.timedelta(hours=7))
c = ReplizClient()


def dump_all(kind, path="/public/schedule"):
    docs, page = [], 1
    while True:
        r = c.get(f"{path}?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
    return docs


def main():
    semua = dump_all("schedule")
    mine = [x for x in semua if (x.get("account") or {}).get("_id") == ACC]
    mine.sort(key=lambda x: x.get("scheduleAt") or "")
    print(f"jadwal DAS Threads: {len(mine)} (dari {len(semua)} total jadwal)")

    st, tipe, media_n, tag_n, jam, dom = (collections.Counter() for _ in range(6))
    ber_link = 0
    errors = []
    for x in mine:
        st[x.get("status")] += 1
        tipe[x.get("type")] += 1
        media_n[len(x.get("medias") or [])] += 1
        d = x.get("description") or ""
        tag_n[len(re.findall(r"#(\w+)", d))] += 1
        if re.search(r"https?://", d):
            ber_link += 1
        for l in re.findall(r"https?://([^/\s]+)", d):
            dom[l] += 1
        t = x.get("scheduleAt") or ""
        try:
            jam[datetime.datetime.fromisoformat(t.replace("Z", "+00:00")).astimezone(WIB).strftime("%H:%M")] += 1
        except Exception:
            pass
        if x.get("status") == "error":
            errors.append((t, x.get("title"), (x.get("errorMessage") or "")[:90]))

    print("status:", dict(st))
    print("tipe:", dict(tipe))
    print("jumlah media per post:", dict(media_n))
    print("jumlah hashtag per post:", dict(tag_n))
    print(f"post ber-link: {ber_link}/{len(mine)}")
    print("jam WIB:", dict(sorted(jam.items())))
    print("domain link:", dom.most_common())
    print("rentang:", mine[0].get("scheduleAt"), "->", mine[-1].get("scheduleAt"))
    print("\n-- error --")
    for e in errors:
        print(" ", e)

    kom = dump_all("comment", "/public/comment")
    punyaku = [k for k in kom if k.get("accountId") == ACC]
    print(f"\nkomentar semua akun: {len(kom)} | untuk DAS: {len(punyaku)}")
    for k in punyaku[:20]:
        print("  -", k.get("createdAt"), (k.get("comment") or {}).get("text"))

    print("\n-- 6 post terakhir --")
    for x in mine[-6:]:
        d = x.get("description") or ""
        tags = re.findall(r"#(\w+)", d)
        print(f"{x.get('scheduleAt')} | {x.get('type')} | {x.get('status')} | len={len(d)} | "
              f"tags={tags} | media={len(x.get('medias') or [])} | "
              f"replies={len(x.get('replies') or [])} | topic={x.get('topic')}")


if __name__ == "__main__":
    main()
