import os

from common import get_env_variable_required, print_message
from src.interface.python_project import (
    PACKAGE_DIR_CI,
    PythonProjectInterface,
    build_whl,
    custom_unit_test,
    exec_command_venv,
    fix_pyproject_version,
    fix_setup_version,
    read_pyproject_toml,
)

NEXUS_URL = "https://nexus.senior.com.br/repository/pypi-hosted/"
NEXUS_USERNAME = get_env_variable_required("NEXUS_USERNAME")
NEXUS_PASSWORD = get_env_variable_required("NEXUS_PASSWORD")


class PythonLib(PythonProjectInterface):

    def compile(self) -> None:
        """
        Gera o artefato do projeto python
        """

        if self.buildable_project.skip_build():
            return

        project_data = read_pyproject_toml()

        if (
            project_data
            and "project" in project_data
            and "version" in project_data["project"]
        ):
            fix_pyproject_version()
            print_message("python whl prepare using pyproject.toml")
            build_whl(".")
        else:
            print_message("Ajustando versão do setup.py")
            fix_setup_version("src/setup.py")
            print_message("python whl prepare using setup.py")
            build_whl("src")

        print_message("validate whl structure")
        exec_command_venv(f"twine check {PACKAGE_DIR_CI}/*")

    def package(self):
        """
        Pega o artefato gerado no stage 'compile' e publica no nexus
        Executado no passo 'release-snapshot' quando branch ou 'release' quando tag
        """

        exec_command_venv(
            f"twine upload --repository-url {NEXUS_URL} -u {NEXUS_USERNAME} -p '{NEXUS_PASSWORD}' {PACKAGE_DIR_CI}/*",
            print_command=False,
            error_message="Falha ao publicar o pacote WHL no Nexus",
        )

    def unit_test(self) -> None:
        """
        Executa os testes unitários
        """

        if self.buildable_project.skip_build():
            return

        custom_unit_test(source="src", python_path="src")
