import configparser
import urllib.request
import urllib.parse
import json
import sys

config = configparser.ConfigParser()
config.read("deploy.ini")

deploy_token = config["deploy"]["token"]
app_url = config["deploy"]["app_url"]


def deploy_call():
    url = f"{app_url}/health/deploy"
    req = urllib.request.Request(
        url,
        method="POST",
        headers={"Authorization": f"Bearer {deploy_token}"},
    )
    try:
        with urllib.request.urlopen(req, timeout=60) as resp:
            return resp.status, json.loads(resp.read())
    except urllib.error.HTTPError as e:
        return e.code, json.loads(e.read())


print("Disparando deploy...")
status, data = deploy_call()
if status != 200:
    print(f"Erro no deploy (HTTP {status}): {data}", file=sys.stderr)
    sys.exit(1)

print(f"Deploy concluído. {data.get('pull', '')}")
