#!/usr/bin/env python3
"""DAS: data kata kunci dari properti Keyword Hero + jejak Google Ads di GA4."""
import os
from google.oauth2 import service_account
from googleapiclient.discovery import build

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

R28 = {"dateRanges": [{"startDate": "2026-08-29", "endDate": "2026-09-25"}]}


def q(prop, dims, mets, urut=None, limit=15, extra=None):
    body = dict(R28)
    body["dimensions"] = [{"name": d} for d in dims]
    body["metrics"] = [{"name": m} for m in mets]
    body["limit"] = limit
    if urut:
        body["orderBys"] = [{"metric": {"metricName": urut}, "desc": True}]
    if extra:
        body.update(extra)
    try:
        return ga.properties().runReport(property=prop, body=body).execute().get("rows", [])
    except Exception as e:
        print(f"   gagal ({dims}): {str(e)[:110]}")
        return []


print("=== KEYWORD HERO (organic keyword) — 28 hari ===")
rows = q(KH, ["customEvent:keywords"], ["eventCount"], "eventCount", 20,
         extra={"dimensionFilter": {"filter": {"fieldName": "eventName", "stringFilter": {"value": "session_start", "matchType": "CONTAINS"}}}})
if not rows:
    rows = q(KH, ["customEvent:keywords"], ["eventCount"], "eventCount", 20)
for row in rows:
    print(f"   {row['metricValues'][0]['value']:>4}x | {row['dimensionValues'][0]['value'][:70]}")

print("\n=== Keyword Hero: kata kunci + posisi + kelas merek (28 hari) ===")
for row in q(KH, ["customEvent:keywords", "customEvent:search_position_dimension", "customEvent:brand_classification"],
             ["eventCount"], "eventCount", 20):
    d = [x["value"] for x in row["dimensionValues"]]
    print(f"   {row['metricValues'][0]['value']:>4}x | pos {d[1]:>5} | {d[2][:12]:<12} | {d[0][:60]}")

print("\n=== JEJAK GOOGLE ADS DI GA4 (28 hari) ===")
print("   kanal paid + kampanye:")
for row in q(GA, ["sessionCampaignName"], ["sessions", "keyEvents"], "sessions", 12,
             extra={"dimensionFilter": {"filter": {"fieldName": "sessionDefaultChannelGroup",
                                                   "stringFilter": {"value": "Paid Search", "matchType": "EXACT"}}}}):
    print(f"      sesi {row['metricValues'][0]['value']:>3} | kunci {row['metricValues'][1]['value']} | {row['dimensionValues'][0]['value'][:56]}")

print("   kejadian konversi Ads:")
for row in q(GA, ["eventName"], ["eventCount"], "eventCount", 40):
    nama = row["dimensionValues"][0]["value"]
    if "ads" in nama.lower() or "conversion" in nama.lower() or "purchase" in nama.lower() or "lead" in nama.lower():
        print(f"      {nama[:60]:<62} {row['metricValues'][0]['value']}")
