import requests
import json

TOKEN = "5|jjkR2nojMZ0vnab8iPNCXtbtlRHP90zXtbDC8Z3m2e95cbf4"
APP_UUID = "e8w040ow8skssoscookowgck" # q1total-backend
BASE_URL = "https://redbull.rede5.com.br/api/v1"

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

# Domínios permitidos (vírgula separada para o backend transformar em lista)
origins = "https://dev.q1site.com.br,https://api-dev.q1site.com.br,http://localhost:3000,http://localhost:3001"

payload = {
    "key": "CORS_ORIGINS",
    "value": origins,
    "is_buildtime": False,
    "is_runtime": True
}

def add_or_update_env():
    # Listar existentes
    envs = requests.get(f"{BASE_URL}/applications/{APP_UUID}/envs", headers=headers).json()
    existing = next((e for e in envs if e['key'] == 'CORS_ORIGINS'), None)
    
    if existing:
        print(f"Atualizando CORS_ORIGINS para: {origins}")
        resp = requests.patch(f"{BASE_URL}/applications/{APP_UUID}/envs/{existing['uuid']}", headers=headers, json=payload)
    else:
        print(f"Criando CORS_ORIGINS com: {origins}")
        resp = requests.post(f"{BASE_URL}/applications/{APP_UUID}/envs", headers=headers, json=payload)
    
    print(f"Status: {resp.status_code}")
    print(resp.text)

    # Redefploy para aplicar
    print("Reiniciando aplicacao...")
    requests.post(f"{BASE_URL}/applications/{APP_UUID}/restart", headers=headers)

if __name__ == "__main__":
    add_or_update_env()
