#!/usr/bin/env python3
"""DAS: (1) pastikan G-TPR5KEQPC4 milik properti GA4 mana, (2) uji klik tombol berpelacak."""
import json, re, urllib.parse, urllib.request, urllib.error

TOKEN = "/home/mantapman/.hermes/profiles/suwarno/workspace/seo-oauth/google_token_seo.json"
from google.oauth2.credentials import Credentials
from google.auth.transport.requests import Request
c = Credentials.from_authorized_user_file(TOKEN, ["https://www.googleapis.com/auth/analytics.readonly"])
if not c.valid:
    c.refresh(Request()); open(TOKEN, "w").write(c.to_json())
H = {"Authorization": f"Bearer {c.token}"}

print("=== properti GA4 yang bisa dibaca ===")
try:
    with urllib.request.urlopen(urllib.request.Request(
            "https://analyticsadmin.googleapis.com/v1beta/accountSummaries?pageSize=50", headers=H), timeout=120) as x:
        d = json.loads(x.read())
    for acc in d.get("accountSummaries", []):
        for p in acc.get("propertySummaries", []):
            pid = p["property"].split("/")[-1]
            nama = p.get("displayName", "")
            try:
                with urllib.request.urlopen(urllib.request.Request(
                        f"https://analyticsadmin.googleapis.com/v1beta/properties/{pid}/dataStreams", headers=H), timeout=90) as y:
                    st = json.loads(y.read())
                id_ukur = [s.get("webStreamData", {}).get("measurementId") for s in st.get("dataStreams", [])]
            except Exception as e:
                id_ukur = [f"gagal: {str(e)[:30]}"]
            tanda = "  ← DIPAKAI DAS" if "G-TPR5KEQPC4" in id_ukur else ""
            print(f"   properti {pid:<12} {nama[:36]:<38} {id_ukur}{tanda}")
except Exception as e:
    print("   gagal:", str(e)[:200])
