#!/usr/bin/env python3
"""Cek GA4 (properti + data) dan tag live untuk leitsurabaya.com."""
import json, os, re, urllib.request
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/analytics.readonly"])
admin = build("analyticsadmin", "v1beta", credentials=creds, cache_discovery=False)

print("=== GA4: akun & properti yang bisa dilihat SA ===")
props = []
for acc in admin.accounts().list().execute().get("accounts", []):
    print("akun:", acc["name"], "|", acc.get("displayName"))
    try:
        for p in admin.properties().list(filter=f"parent:{acc['name']}").execute().get("properties", []):
            props.append(p)
    except Exception as e:
        print("   (gagal list properti:", str(e)[:120], ")")
for p in props:
    print("   ", p["name"], "|", p.get("displayName"))

leit = [p for p in props if "leit" in json.dumps(p).lower()]
print("\nproperti LEIT di GA4:", [(p["name"], p["displayName"]) for p in leit])

data = build("analyticsdata", "v1beta", credentials=creds, cache_discovery=False)
end = date.today() - timedelta(days=1)
start = end - timedelta(days=27)
for p in leit:
    try:
        ds = admin.properties().dataStreams().list(parent=p["name"]).execute().get("dataStreams", [])
        ids = [d.get("webStreamData", {}).get("measurementId") for d in ds]
        print(f"\n{p['displayName']} [{p['name']}] stream: {ids}")
        r = data.properties().runReport(property=p["name"], body={
            "dateRanges": [{"startDate": start.isoformat(), "endDate": end.isoformat()}],
            "metrics": [{"name": "sessions"}, {"name": "totalUsers"}, {"name": "screenPageViews"}],
        }).execute()
        print("   28d:", [m["value"] for m in r.get("rows", [{}])[0].get("metricValues", [])] if r.get("rows") else "TIDAK ADA DATA")
        ch = data.properties().runReport(property=p["name"], body={
            "dateRanges": [{"startDate": start.isoformat(), "endDate": end.isoformat()}],
            "dimensions": [{"name": "sessionDefaultChannelGroup"}],
            "metrics": [{"name": "sessions"}],
            "orderBys": [{"metric": {"metricName": "sessions"}, "desc": True}], "limit": 8}).execute()
        for row in ch.get("rows", []):
            print("     ", row["dimensionValues"][0]["value"], row["metricValues"][0]["value"])
    except Exception as e:
        print("   ERROR report:", str(e)[:200])

print("\n=== TAG LIVE di leitsurabaya.com ===")
req = urllib.request.Request("https://www.leitsurabaya.com/", headers={"User-Agent": "Mozilla/5.0", "Cache-Control": "no-cache"})
html = urllib.request.urlopen(req, timeout=90).read().decode("utf-8", "replace")
ids = sorted(set(re.findall(r"\b(?:GTM|GT|G|UA|AW)-[A-Z0-9]{6,}\b", html)))
print("ID tag ditemukan:", ids)
print("Site Kit:", "ya" if "site-kit" in html.lower() else "tidak")
print("gtag config:", re.findall(r"gtag\(\s*['\"]config['\"]\s*,\s*['\"]([A-Z0-9-]+)", html))
verif = re.findall(r'<meta name="google-site-verification" content="([^"]+)"', html)
print("google-site-verification:", verif)
