import requests
import json

TOKEN = "5|jjkR2nojMZ0vnab8iPNCXtbtlRHP90zXtbDC8Z3m2e95cbf4"
BASE_URL = "https://redbull.rede5.com.br/api/v1"
SERVICE_UUID = "u48o4wwww84ksw080cc04048"

headers = {
    "Authorization": f"Bearer {TOKEN}",
    "Content-Type": "application/json"
}

def update_env(key, value):
    # Primeiro buscar o UUID da variavel existente
    envs = requests.get(f"{BASE_URL}/services/{SERVICE_UUID}/envs", headers=headers).json()
    env_uuid = next((e['uuid'] for e in envs if e['key'] == key), None)
    
    payload = {
        "key": key,
        "value": value,
        "is_buildtime": True,
        "is_runtime": True
    }
    
    if env_uuid:
        # Update existente
        print(f"Atualizando {key}...")
        resp = requests.patch(f"{BASE_URL}/services/{SERVICE_UUID}/envs/{env_uuid}", headers=headers, json=payload)
    else:
        # Criar nova
        print(f"Criando {key}...")
        resp = requests.post(f"{BASE_URL}/services/{SERVICE_UUID}/envs", headers=headers, json=payload)
    
    print(resp.status_code, resp.text)

if __name__ == "__main__":
    update_env("SERVICE_FQDN_N8N", "https://n8n.rede5.com.br")
    update_env("N8N_PROTOCOL", "https")
    
    # Restart para aplicar
    print("Reiniciando servico...")
    requests.post(f"{BASE_URL}/services/{SERVICE_UUID}/restart", headers=headers)
