#!/usr/bin/env python3
"""Tambah trigger klik WhatsApp + form submission di GTM, sambungkan ke tag GA4, 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"
C = gtm.accounts().containers()
ws = C.workspaces().list(parent=CONTAINER).execute().get("workspace", [])
WS = ws[-1]["path"]
print("workspace:", ws[-1]["name"], "|", WS)

trig = {t["name"]: t["triggerId"] for t in C.workspaces().triggers().list(parent=WS).execute().get("trigger", [])}
tags = {t["name"]: t for t in C.workspaces().tags().list(parent=WS).execute().get("tag", [])}
print("trigger lama:", trig)
print("tag lama:", list(tags))

# 1. trigger klik link WhatsApp
body_klik = {
    "name": "Klik - Tombol WhatsApp",
    "type": "LINK_CLICK",
    "filter": [{"type": "CONTAINS", "parameter": [
        {"type": "TEMPLATE", "key": "arg0", "value": "{{Click URL}}"},
        {"type": "TEMPLATE", "key": "arg1", "value": "wa.me"}]}],
}
k1 = C.workspaces().triggers().create(parent=WS, body=body_klik).execute()
print("trigger klik wa.me →", k1["triggerId"])

body_klik2 = {
    "name": "Klik - Tombol WhatsApp (whatsapp.com)",
    "type": "LINK_CLICK",
    "filter": [{"type": "CONTAINS", "parameter": [
        {"type": "TEMPLATE", "key": "arg0", "value": "{{Click URL}}"},
        {"type": "TEMPLATE", "key": "arg1", "value": "whatsapp.com"}]}],
}
k2 = C.workspaces().triggers().create(parent=WS, body=body_klik2).execute()
print("trigger klik whatsapp.com →", k2["triggerId"])

# 2. trigger kirim formulir
body_form = {"name": "Formulir - Semua Form", "type": "FORM_SUBMISSION",
             "filter": [{"type": "MATCH_REGEX", "parameter": [
                 {"type": "TEMPLATE", "key": "arg0", "value": "{{Form ID}}"},
                 {"type": "TEMPLATE", "key": "arg1", "value": ".*"}]}]}
f1 = C.workspaces().triggers().create(parent=WS, body=body_form).execute()
print("trigger form submission →", f1["triggerId"])

# 3. sambungkan ke tag yang sudah ada
def sambung(nama_tag, tambahan):
    t = tags.get(nama_tag)
    if not t:
        print("  tag tidak ketemu:", nama_tag); return
    firing = sorted(set([str(x) for x in (t.get("firingTriggerId") or [])] + [str(x) for x in tambahan]))
    C.workspaces().tags().update(path=t["path"], body=dict(t, firingTriggerId=firing)).execute()
    print(f"  {nama_tag} sekarang menyala pada trigger {firing}")

sambung("GA4 - manual_event_CONTACT (WhatsApp/Telepon)", [k1["triggerId"], k2["triggerId"]])
sambung("GA4 - qualify_lead (kirim formulir)", [f1["triggerId"]])

# 4. versi + publish
ver = C.workspaces().create_version(path=WS, body={"name": "v5 - trigger klik WhatsApp + form",
                                                   "notes": "Tambah Click trigger (wa.me / whatsapp.com) dan Form Submission."}).execute()
cv = ver.get("containerVersion", {})
print(f"\nversi {cv.get('containerVersionId')} | tag={len(cv.get('tag', []))} trigger={len(cv.get('trigger', []))}")
C.versions().publish(path=f"{CONTAINER}/versions/{cv.get('containerVersionId')}").execute()
lv = C.versions().live(parent=CONTAINER).execute()
print("LIVE:", lv.get("name"))
for t in lv.get("tag", []):
    print("  TAG:", t.get("name"), "| trigger", t.get("firingTriggerId"))
