#!/usr/bin/env python3
"""Bangun tag konversi di container GTM-WQX6PGNR (draft di workspace dulu)."""
import json, os
from google.oauth2 import service_account
from googleapiclient.discovery import build

SCOPES = ["https://www.googleapis.com/auth/tagmanager.edit.containers",
          "https://www.googleapis.com/auth/tagmanager.publish",
          "https://www.googleapis.com/auth/tagmanager.readonly"]
creds = service_account.Credentials.from_service_account_file(
    os.path.expanduser("~/.hermes/gsc_service_account.json"), scopes=SCOPES)
gtm = build("tagmanager", "v2", credentials=creds, cache_discovery=False)

CONTAINER = "accounts/6303077991/containers/224445829"   # GTM-WQX6PGNR
GA4 = "G-5YGFJFBNH1"

# 0. workspace
ws = gtm.accounts().containers().workspaces().list(parent=CONTAINER).execute().get("workspace", [])
WS = ws[0]["path"]
print("workspace:", ws[0]["name"], "|", WS)

# 1. trigger custom event
TRIGGERS = {}
for ev, nama in (("manual_event_contact", "Custom Event - manual_event_contact"),
                 ("qualify_lead", "Custom Event - qualify_lead")):
    body = {
        "name": nama,
        "type": "CUSTOM_EVENT",
        "customEventFilter": [{"type": "EQUALS", "parameter": [
            {"type": "TEMPLATE", "key": "arg0", "value": "{{_event}}"},
            {"type": "TEMPLATE", "key": "arg1", "value": ev}]}],
    }
    t = gtm.accounts().containers().workspaces().triggers().create(parent=WS, body=body).execute()
    TRIGGERS[ev] = t["triggerId"]
    print(f"trigger dibuat: {nama} → id {t['triggerId']}")

# 2. tag GA4 Event
TAGS = {}
for ev, nama_tag, trg in (("manual_event_CONTACT", "GA4 - manual_event_CONTACT (WhatsApp/Telepon)", "manual_event_contact"),
                          ("qualify_lead", "GA4 - qualify_lead (kirim formulir)", "qualify_lead")):
    body = {
        "name": nama_tag,
        "type": "gaawe",
        "parameter": [
            {"type": "TEMPLATE", "key": "eventName", "value": ev},
            {"type": "TEMPLATE", "key": "measurementId", "value": GA4},
        ],
        "firingTriggerId": [TRIGGERS[trg]],
    }
    t = gtm.accounts().containers().workspaces().tags().create(parent=WS, body=body).execute()
    TAGS[ev] = t["tagId"]
    print(f"tag dibuat: {nama_tag} → id {t['tagId']} | trigger {TRIGGERS[trg]}")

print(json.dumps({"workspace": WS, "triggers": TRIGGERS, "tags": TAGS}, indent=1))
