#!/usr/bin/env python3
"""Uji hak tulis service account di kedua container studiosoft.id."""
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.publish"])
gtm = build("tagmanager", "v2", credentials=creds, cache_discovery=False)

for label, path in (("GTM-WQX6PGNR", "accounts/6303077991/containers/224445829"),
                    ("GTM-PZBR35TB", "accounts/6269687730/containers/206637156")):
    print(f"--- {label} ({path})")
    try:
        ws = gtm.accounts().containers().workspaces().list(parent=path).execute().get("workspace", [])
        if not ws:
            print("    tidak ada workspace"); continue
        wsp = ws[0]["path"]
        print("    workspace:", ws[0]["name"])
        v = gtm.accounts().containers().workspaces().variables().create(parent=wsp, body={
            "name": "uji-hak-tulis-hermes", "type": "v",
            "parameter": [{"type": "INTEGER", "key": "value", "value": "1"}]}).execute()
        print("    ✅ BISA MENULIS — variable uji id", v.get("variableId"))
        gtm.accounts().containers().workspaces().variables().delete(path=v["path"]).execute()
        print("    variable uji dihapus (bersih)")
    except Exception as e:
        print("    ❌ TIDAK BISA MENULIS:", str(e)[:180])
