#!/usr/bin/env python3
"""StudioSoft kesiapan Google Ads: konversi GA4, link Google Ads, metrik 28d, keyword komersial GSC."""
import os, json
from datetime import date, timedelta
from google.oauth2 import service_account
from googleapiclient.discovery import build

SA = os.path.expanduser("~/.hermes/gsc_service_account.json")
creds = service_account.Credentials.from_service_account_file(
    SA, scopes=["https://www.googleapis.com/auth/webmasters.readonly",
                "https://www.googleapis.com/auth/analytics.readonly"])
gsc = build("webmasters", "v3", credentials=creds, cache_discovery=False)
admin = build("analyticsadmin", "v1beta", credentials=creds, cache_discovery=False)
data = build("analyticsdata", "v1beta", credentials=creds, cache_discovery=False)

PROP = "properties/478760195"
S = "https://studiosoft.id/"
e = date.today() - timedelta(days=2)
S28, END = (e - timedelta(days=27)).isoformat(), e.isoformat()

print("=== KONFIGURASI GA4 studiosoft.id ===")
try:
    ke = admin.properties().keyEvents(parent=PROP).execute().get("keyEvents", [])
    print(f"key events (konversi): {len(ke)}")
    for k in ke:
        print(f"   - {k.get('eventName')} | counting: {k.get('countingMethod')}")
except Exception as ex:
    print("  keyEvents error:", str(ex)[:160])

try:
    links = admin.properties().googleAdsLinks(parent=PROP).execute().get("googleAdsLinks", [])
    print(f"link Google Ads: {len(links)}")
    for l in links:
        print("   -", l.get("customerId"), l.get("adsPersonalizationEnabled"), l.get("canManageClients"))
except Exception as ex:
    print("  googleAdsLinks error:", str(ex)[:160])

try:
    for ds in admin.properties().dataStreams(parent=PROP).execute().get("dataStreams", []):
        print(f"data stream: {ds.get('displayName')} | {ds.get('webStreamData', {}).get('measurementId')} | {ds.get('webStreamData', {}).get('defaultUri')}")
except Exception as ex:
    print("  dataStreams error:", str(ex)[:160])


def rep(body):
    return data.properties().runReport(property=PROP, body=body).execute()


print("\n=== GA4 28 hari (organic vs keseluruhan) ===")
r = rep({"dateRanges": [{"startDate": S28, "endDate": END}],
         "metrics": [{"name": m} for m in ("sessions", "totalUsers", "screenPageViews", "engagementRate", "averageSessionDuration")]})
print("  total:", [m["value"] for m in r["rows"][0]["metricValues"]] if r.get("rows") else "kosong")
r = rep({"dateRanges": [{"startDate": S28, "endDate": END}],
         "dimensions": [{"name": "sessionDefaultChannelGroup"}], "metrics": [{"name": "sessions"}],
         "orderBys": [{"metric": {"metricName": "sessions"}, "desc": True}]})
for x in r.get("rows", []):
    print(f"   {x['dimensionValues'][0]['value']:<22} {x['metricValues'][0]['value']}")

print("\n  event yang tercatat 28d (calon konversi):")
r = rep({"dateRanges": [{"startDate": S28, "endDate": END}], "dimensions": [{"name": "eventName"}],
         "metrics": [{"name": "eventCount"}], "orderBys": [{"metric": {"metricName": "eventCount"}, "desc": True}], "limit": 15})
for x in r.get("rows", []):
    print(f"   {x['dimensionValues'][0]['value']:<34} {x['metricValues'][0]['value']}")

print("\n=== GSC: keyword bernilai komersial (90 hari) ===")
e90 = (e - timedelta(days=89)).isoformat()
rows = gsc.searchanalytics().query(siteUrl=S, body={"startDate": e90, "endDate": END, "dimensions": ["query"], "rowLimit": 5000}).execute().get("rows", [])
JUAL = ("jasa", "bikin", "buat website", "pembuatan website", "seo", "digital marketing", "iklan", "agency", "agensi",
        "konsultan", "optimasi", "google maps", "landing page", "toko online", "company profile")
beli = [r for r in rows if any(k in r["keys"][0].lower() for k in JUAL)]
beli.sort(key=lambda r: -r["impressions"])
print(f"query bernilai jual: {len(beli)} dari {len(rows)}")
for r in beli[:25]:
    print(f"   {int(r['impressions']):>5} imp | {int(r['clicks'])} klik | pos {r['position']:>5.1f} | {r['keys'][0]}")

INFO = ("apa", "cara", "belajar", "gratis", "contoh", "adalah", "pengertian", "lowongan", "kursus", "template", "arti", "fungsi")
neg = [r for r in rows if any(k in r["keys"][0].lower() for k in INFO)]
neg.sort(key=lambda r: -r["impressions"])
print(f"\n=== calon negative keyword (informasional, {len(neg)} query) ===")
for r in neg[:18]:
    print(f"   {int(r['impressions']):>5} imp | {r['keys'][0]}")

json.dump({"komersial": [{"q": r["keys"][0], "imp": int(r["impressions"]), "klik": int(r["clicks"]), "pos": r["position"]} for r in beli],
           "informasional": [{"q": r["keys"][0], "imp": int(r["impressions"])} for r in neg]},
          open("/home/mantapman/.hermes/profiles/atun/workspace/studiosoft_ads_keywords.json", "w"), indent=1, ensure_ascii=False)
