#!/usr/bin/env python3
"""Tambah Google Tag (GA4 config) di container — tanpa page_view ganda."""
import os
from google.oauth2 import service_account
from googleapiclient.discovery import build

creds = service_account.Credentials.from_service_account_file(
    os.path.expanduser("~/.hermes/gsc_service_account.json"),
    scopes=["https://www.googleapis.com/auth/tagmanager.edit.containers",
            "https://www.googleapis.com/auth/tagmanager.edit.containerversions",
            "https://www.googleapis.com/auth/tagmanager.publish",
            "https://www.googleapis.com/auth/tagmanager.readonly"])
gtm = build("tagmanager", "v2", credentials=creds, cache_discovery=False)
CONTAINER = "accounts/6303077991/containers/224445829"
WS = CONTAINER + "/workspaces/2"
GA4 = "G-5YGFJFBNH1"

print("=== trigger yang ada di workspace ===")
for t in gtm.accounts().containers().workspaces().triggers().list(parent=WS).execute().get("trigger", []):
    print(f"  [{t['triggerId']}] {t['name']} | {t['type']}")

# trigger bawaan "All Pages" di GTM selalu punya id ini
ALL_PAGES = "2147479553"
print(f"\nmemakai trigger All Pages (id bawaan {ALL_PAGES})")

body = {
    "name": "Google Tag - GA4 StudioSoft",
    "type": "googtag",
    "parameter": [
        {"type": "TEMPLATE", "key": "tagId", "value": GA4},
        {"type": "BOOLEAN", "key": "sendPageView", "value": "false"},
    ],
    "firingTriggerId": [ALL_PAGES],
}
try:
    t = gtm.accounts().containers().workspaces().tags().create(parent=WS, body=body).execute()
    print(f"✅ Google Tag dibuat → id {t['tagId']} (page_view dimatikan supaya tidak dobel)")
except Exception as e:
    print("❌ gagal:", str(e)[:300])

print("\n=== tag di workspace sekarang ===")
for t in gtm.accounts().containers().workspaces().tags().list(parent=WS).execute().get("tag", []):
    print(f"  [{t['tagId']}] {t['name']} | {t['type']} | trigger {t.get('firingTriggerId')}")
