#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Statistik nyata per akun dari Repliz: GET /public/account/{accountId}/statistic.

Ini sumber angka VIEWS / followers yang selama ini dianggap tidak ada (dulu disebut
"endpoint insight menolak id akun" karena alamatnya salah: yang benar pakai PATH
/{accountId}/statistic, bukan query ?accountId=).

Docs: https://docs.repliz.com/api/account/get-statistic-account.html
  - Threads -> likes, replies, reposts, quotes, followersCount, views{total,graphs[]}, clicks{total,links[]}
  - IG      -> reach, views, likes, saves, shares, totalInteractions, ...
  - TikTok  -> followersCount, metrics[] harian

Pakai:
  python3 stat_akun_repliz.py                 # semua akun Threads
  python3 stat_akun_repliz.py --platform all   # semua akun semua platform
  python3 stat_akun_repliz.py --akun ukyhandoko --json out.json
"""
import argparse
import datetime
import json
import sys

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
sys.path.insert(0, WS)
from repliz_client import ReplizClient  # noqa: E402


def semua_halaman(c, path, maks=40):
    docs, page = [], 1
    while page <= maks:
        r = None
        for _ in range(10):
            try:
                r = c.get(f"{path}?page={page}&limit=100")
                break
            except Exception:
                r = None
        if r is None:
            break
        d = r.get("docs") or []
        docs += d
        if not d or page * 100 >= (r.get("totalDocs") or 0):
            break
        page += 1
    return docs


def jml_rentang(graphs, hari_awal, hari_akhir):
    """Total value graphs antara tanggal (inklusif), format YYYY-MM-DD."""
    t = 0
    for g in graphs or []:
        d = str(g.get("date") or "")[:10]
        if hari_awal <= d <= hari_akhir:
            t += g.get("value") or 0
    return t


def main():
    p = argparse.ArgumentParser()
    p.add_argument("--akun")
    p.add_argument("--platform", default="threads")
    p.add_argument("--json")
    a = p.parse_args()

    c = ReplizClient()
    akun = semua_halaman(c, "/public/account")
    if a.akun:
        k = a.akun.lower()
        akun = [x for x in akun if k in (x.get("username") or "").lower()
                or k in (x.get("name") or "").lower()]
    elif a.platform != "all":
        akun = [x for x in akun if x.get("type") == a.platform]

    hari_ini = datetime.datetime.now(datetime.timezone.utc).date()
    d7 = (hari_ini - datetime.timedelta(days=6)).isoformat()
    d14 = (hari_ini - datetime.timedelta(days=13)).isoformat()
    d30 = (hari_ini - datetime.timedelta(days=29)).isoformat()
    besok = hari_ini.isoformat()

    hasil = {}
    for x in akun:
        aid = x["_id"]
        try:
            st = c.get(f"/public/account/{aid}/statistic")
        except Exception as e:
            print(f"\n@{x.get('username')} ({x.get('type')}) → ❌ {str(e)[:120]}")
            hasil[aid] = {"error": str(e)[:200]}
            continue
        v = st.get("views")
        if isinstance(v, dict):
            g = v.get("graphs") or []
            total_view = v.get("total")
        else:
            g = []
            total_view = v
        v7 = jml_rentang(g, d7, besok)
        v14 = jml_rentang(g, d14, besok)
        v30 = jml_rentang(g, d30, besok)
        sebelum7 = v14 - v7
        hasil[aid] = dict(nama=x.get("username"), platform=x.get("type"), stat=st,
                          v7=v7, v14=v14, v30=v30, v_sebelum7=sebelum7)
        print(f"\n=== @{x.get('username')} ({x.get('type')}) ===")
        print(f"  followers      : {st.get('followersCount')}")
        print(f"  views 7 hari   : {v7}   | 7 hari sebelumnya: {sebelum7} "
              f"({'NAIK' if v7 >= sebelum7 else 'TURUN'} {abs(v7-sebelum7)})")
        print(f"  views 14 hari  : {v14} | 30 hari: {v30} (total laporan: {total_view})")
        print(f"  likes={st.get('likes')} replies={st.get('replies')} reposts={st.get('reposts')} "
              f"quotes={st.get('quotes')} reach={st.get('reach')}")
        klik = (st.get("clicks") or {})
        if klik:
            print(f"  klik link: {klik.get('total')} (links={len(klik.get('links') or [])})")
        if g:
            print("  harian        :", " ".join(f"{str(z.get('date'))[5:10]}={z.get('value')}" for z in g[-10:]))

    if a.json:
        with open(a.json, "w") as f:
            json.dump(hasil, f, ensure_ascii=False, indent=1)
        print(f"\n(json disimpan: {a.json})")


if __name__ == "__main__":
    main()
