#!/usr/bin/env python3
"""DAS — data GA4 nyata: kanal, halaman pendaratan, kejadian penting, tren sesi organik."""
import os
from datetime import date, timedelta

from google.oauth2 import service_account
from googleapiclient.discovery import build

PROP = "properties/443064659"
creds = service_account.Credentials.from_service_account_file(
    os.path.expanduser("~/.hermes/gsc_service_account.json"),
    scopes=["https://www.googleapis.com/auth/analytics.readonly"])
ga = build("analyticsdata", "v1beta", credentials=creds, cache_discovery=False)
AKHIR = date.today() - timedelta(days=2)


def run(dims, mets, awal, akhir, limit=200, order=None):
    body = {"dateRanges": [{"startDate": awal.isoformat(), "endDate": akhir.isoformat()}],
            "dimensions": [{"name": d} for d in dims],
            "metrics": [{"name": m} for m in mets],
            "limit": limit}
    if order:
        body["orderBys"] = [{"metric": {"metricName": order}, "desc": True}]
    try:
        return ga.properties().runReport(property=PROP, body=body).execute().get("rows", [])
    except Exception as e:
        print(f"  ❌ GA4 error: {str(e)[:180]}")
        return []


print(f"=== DAS — GA4 (data s/d {AKHIR}) ===")

print("\n1. SESI PER KANAL")
for label, a, b in (("28 hari terakhir", AKHIR - timedelta(days=27), AKHIR),
                    ("28 hari sebelumnya", AKHIR - timedelta(days=55), AKHIR - timedelta(days=28)),
                    ("Juli (sebelum jatuh)", date(2026, 7, 1), date(2026, 7, 28))):
    rows = run(["sessionDefaultChannelGroup"], ["sessions", "totalUsers", "keyEvents"], a, b, order="sessions")
    print(f"   {label}:")
    for r in rows[:6]:
        print(f"      {r['dimensionValues'][0]['value']:<22} sesi {r['metricValues'][0]['value']:>5} | "
              f"pengguna {r['metricValues'][1]['value']:>5} | key event {r['metricValues'][2]['value']:>4}")

print("\n2. KEJADIAN TERBANYAK (28 hari)")
for r in run(["eventName"], ["eventCount"], AKHIR - timedelta(days=27), AKHIR, order="eventCount")[:15]:
    print(f"   {r['dimensionValues'][0]['value']:<26} {r['metricValues'][0]['value']}")

print("\n3. HALAMAN PENDARATAN (28 hari, sesi terbanyak)")
for r in run(["landingPagePlusQueryString"], ["sessions", "totalUsers", "keyEvents"],
             AKHIR - timedelta(days=27), AKHIR, limit=15, order="sessions"):
    print(f"   {r['metricValues'][0]['value']:>5} sesi | {r['metricValues'][2]['value']:>3} key event | "
          f"{r['dimensionValues'][0]['value'][:70]}")

print("\n4. SESI ORGANIK PER PEKAN (12 pekan)")
for i in range(11, -1, -1):
    b = AKHIR - timedelta(days=7 * i)
    a = b - timedelta(days=6)
    rows = run(["sessionDefaultChannelGroup"], ["sessions"], a, b)
    org = sum(int(r["metricValues"][0]["value"]) for r in rows
              if "Organic" in r["dimensionValues"][0]["value"])
    tot = sum(int(r["metricValues"][0]["value"]) for r in rows)
    print(f"   {a} s/d {b} | organik {org:>4} | total {tot:>4} | {'█' * min(40, org // 2)}")
