import requests
import json

TOKEN = "5|jjkR2nojMZ0vnab8iPNCXtbtlRHP90zXtbDC8Z3m2e95cbf4"
APP_UUID = "y0wccwwsko4socokk804s0ww" # q1site-frontend
BASE_URL = "https://redbull.rede5.com.br/api/v1"

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

envs = [
    {"key": "NEXT_PUBLIC_API_URL", "value": "https://api-dev.q1site.com.br/api/v1"},
    {"key": "NEXT_PUBLIC_TENANT_SUBDOMAIN", "value": "q1sites"},
    {"key": "NEXT_PUBLIC_ENVIRONMENT", "value": "production"}
]

def setup_frontend():
    # 1. Listar variáveis atuais
    print("Buscando variáveis existentes...")
    current_envs = requests.get(f"{BASE_URL}/applications/{APP_UUID}/envs", headers=headers).json()
    env_map = {e['key']: e['uuid'] for e in current_envs}

    for env in envs:
        payload = {
            "key": env["key"],
            "value": env["value"],
            "is_buildtime": True, # CRÍTICO para Next.js
            "is_runtime": True
        }
        
        if env["key"] in env_map:
            print(f"Atualizando {env['key']}...")
            requests.patch(f"{BASE_URL}/applications/{APP_UUID}/envs/{env_map[env['key']]}", headers=headers, json=payload)
        else:
            print(f"Criando {env['key']}...")
            requests.post(f"{BASE_URL}/applications/{APP_UUID}/envs", headers=headers, json=payload)

    # 2. Disparar Deploy (Necessário para reconstruir o Next.js com as novas variáveis)
    print("Disparando novo deploy...")
    deploy_resp = requests.get(f"{BASE_URL}/deploy?uuid={APP_UUID}", headers=headers)
    print(f"Status do Deploy: {deploy_resp.status_code}")
    print(deploy_resp.text)

if __name__ == "__main__":
    setup_frontend()
