import sys

import requests

sys.path.append("./senior-ci")

from common import (
    exec_command,
    exit_message,
    get_env_variable,
    get_env_variable_required,
    get_version_from_gitlab,
)
from common.extensions import Extensions

NEXUS_HOST = "https://nexus.senior.com.br"
NEXUS_HELM_REPOSITORY = "helm-hosted"
nexus_username = get_env_variable_required("NEXUS_USERNAME")
nexus_password = get_env_variable_required("NEXUS_PASSWORD")

sci_argocd_project = get_env_variable_required("SCI_ARGOCD_PROJECT")
sci_argocd_dest_name = get_env_variable_required("SCI_ARGOCD_DEST_NAME")
sci_argocd_sync_options = get_env_variable(
    "SCI_ARGOCD_SYNC_OPT",
    "--sync-policy automated --auto-prune --sync-option CreateNamespace=true",
)
sci_argocd_app_name = get_env_variable_required("SCI_ARGOCD_APP_NAME")

sci_namespace = get_env_variable_required("SCI_NAMESPACE")
sci_svc_name = get_env_variable_required("SCI_SVC_NAME")

service_version = get_version_from_gitlab()

sci_argocd_wait_timeout = get_env_variable(
    "SCI_ARGOCD_WAIT_TIMEOUT",
    "300",
)


def _get_latest_chart_version():
    url = f"{NEXUS_HOST}/service/rest/v1/search?sort=version&repository={NEXUS_HELM_REPOSITORY}&name={sci_svc_name}"

    response = requests.get(
        url, auth=(nexus_username, nexus_password), timeout=60
    ).json()

    if len(response["items"]) == 0:
        exit_message(
            f"Não foi possível encontrar nenhuma release do chart {sci_svc_name} no Nexus."
        )

    return response["items"][0]["version"]


chart_version = get_env_variable("SCI_CHART_VERSION", _get_latest_chart_version())

extensions = Extensions()

extensions.before_deploy()

exec_command(
    f"argocd app create {sci_argocd_app_name} --upsert {sci_argocd_sync_options} "
    f"--repo {NEXUS_HOST}/repository/{NEXUS_HELM_REPOSITORY}/ "
    f"--helm-chart {sci_svc_name} --revision {chart_version} "
    f"--release-name {sci_svc_name} --project {sci_argocd_project} "
    f"--dest-name {sci_argocd_dest_name} --dest-namespace {sci_namespace} "
    f"--helm-set image.tag={service_version}",
    error_message="Não foi possível realizar o deploy. Verifique nos logs acima a possível causa",
)

exec_command(
    f"argocd app wait {sci_argocd_app_name} --timeout {sci_argocd_wait_timeout}"
)

extensions.after_deploy()
