#!/usr/bin/env python3
"""TSLaw GA4 lengkap: ringkasan, kanal, halaman, perangkat, kota, kejadian, realtime."""
import os
from google.oauth2 import service_account
from googleapiclient.discovery import build

KEY = os.path.expanduser("~/.hermes/gsc_service_account.json")
PROP = "properties/537990618"
ga = build("analyticsdata", "v1beta",
           credentials=service_account.Credentials.from_service_account_file(
               KEY, scopes=["https://www.googleapis.com/auth/analytics.readonly"]), cache_discovery=False)


def rep(dims, mets, mulai, akhir, limit=12, urut=None):
    b = {"dateRanges": [{"startDate": mulai, "endDate": akhir}],
         "dimensions": [{"name": d} for d in dims],
         "metrics": [{"name": m} for m in mets], "limit": limit}
    if urut:
        b["orderBys"] = [{"metric": {"metricName": urut}, "desc": True}]
    return ga.properties().runReport(property=PROP, body=b).execute().get("rows", [])


for label, mulai, akhir in (("28 HARI", "2026-08-29", "2026-09-25"), ("90 HARI", "2026-06-28", "2026-09-25")):
    print(f"\n================ {label} ================")
    r = rep([], ["sessions", "totalUsers", "screenPageViews", "keyEvents", "averageSessionDuration", "engagementRate"],
            mulai, akhir, limit=1)
    if r:
        v = [x["value"] for x in r[0]["metricValues"]]
        print(f"  sesi {v[0]} | pengguna {v[1]} | halaman dilihat {v[2]} | kejadian kunci {v[3]} | "
              f"durasi rata-rata {round(float(v[4]))}s | engagement {round(float(v[5])*100)}%")

    print("  ── kanal ──")
    for row in rep(["sessionDefaultChannelGroup"], ["sessions", "totalUsers", "keyEvents"], mulai, akhir, 10, "sessions"):
        d = row["dimensionValues"][0]["value"]; v = [x["value"] for x in row["metricValues"]]
        print(f"     {d:<18} sesi {v[0]:>4} | pengguna {v[1]:>4} | kunci {v[2]}")

    print("  ── halaman teratas ──")
    for row in rep(["pagePath"], ["screenPageViews", "totalUsers", "averageSessionDuration"], mulai, akhir, 10, "screenPageViews"):
        d = row["dimensionValues"][0]["value"]; v = [x["value"] for x in row["metricValues"]]
        print(f"     {d[:56]:<58} view {v[0]:>4} | pengguna {v[1]:>4} | {round(float(v[2]))}s")

    print("  ── perangkat ──")
    for row in rep(["deviceCategory"], ["sessions", "engagementRate"], mulai, akhir, 5, "sessions"):
        d = row["dimensionValues"][0]["value"]; v = [x["value"] for x in row["metricValues"]]
        print(f"     {d:<10} sesi {v[0]:>4} | engagement {round(float(v[1])*100)}%")

print("\n================ KOTA (90 hari) ================")
for row in rep(["city"], ["sessions", "averageSessionDuration"], "2026-06-28", "2026-09-25", 12, "sessions"):
    d = row["dimensionValues"][0]["value"]; v = [x["value"] for x in row["metricValues"]]
    print(f"   {d[:28]:<30} sesi {v[0]:>4} | durasi {round(float(v[1]))}s")

print("\n================ KEJADIAN (90 hari) ================")
for row in rep(["eventName"], ["eventCount"], "2026-06-28", "2026-09-25", 25, "eventCount"):
    print(f"   {row['dimensionValues'][0]['value']:<28} {row['metricValues'][0]['value']}")

print("\n================ REALTIME (30 menit terakhir) ================")
try:
    rt = ga.properties().runRealtimeReport(property=PROP, body={
        "dimensions": [{"name": "unifiedScreenName"}],
        "metrics": [{"name": "activeUsers"}]}).execute().get("rows", [])
    if rt:
        for row in rt:
            print(f"   {row['dimensionValues'][0]['value'][:50]:<52} pengguna aktif {row['metricValues'][0]['value']}")
    else:
        print("   tidak ada pengguna aktif saat ini")
except Exception as e:
    print("   gagal:", str(e)[:120])
