#!/usr/bin/env python3
"""Tambah Google Tag di workspace 3, buat versi baru, publish."""
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/3"
GA4 = "G-5YGFJFBNH1"
ALL_PAGES = "2147479553"

# 1. Google Tag (GA4 config) — page_view dimatikan karena Site Kit sudah mengirimnya
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']}")
except Exception as e:
    print("❌ gagal bikin Google Tag:", str(e)[:300])

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

# 2. versi + publish
ver = gtm.accounts().containers().workspaces().create_version(
    path=WS, body={"name": "Pelacakan konversi v3 (Google Tag + GA4 Event)",
                   "notes": "Tambah Google Tag GA4 (sendPageView=false) sebagai induk tag event."}).execute()
cv = ver.get("containerVersion", {})
print(f"\nversi dibuat: {cv.get('containerVersionId')} | tag={len(cv.get('tag', []))}")
gtm.accounts().containers().versions().publish(path=f"{CONTAINER}/versions/{cv.get('containerVersionId')}").execute()
lv = gtm.accounts().containers().versions().live(parent=CONTAINER).execute()
print("versi LIVE:", lv.get("name"), "| tag:", [t.get("name") for t in lv.get("tag", [])])
