from datetime import datetime, timedelta

from common import get_env_variable, get_env_variable_required
from common.graphql_client import GraphqlClient

from .custom_issue import CustomIssue


class CheckConfigFiles(object):
    def __init__(self, client_graphql: GraphqlClient = GraphqlClient()) -> None:
        self.client_graphql = client_graphql

    def check(self):
        """Check if sonar and project files are configured accordingly"""

        query = """
            query ($projectId: Int!, $branch: String!, $projectType: ProjectTypeEnum!) {
                checkConfigFiles(projectId: $projectId, branch: $branch, projectType: $projectType) {
                    reason
                    success
                }
            }
        """

        params = {
            "projectId": int(get_env_variable_required("CI_PROJECT_ID")),
            "branch": get_env_variable_required("CI_COMMIT_REF_NAME"),
            "projectType": get_env_variable_required("SCI_PROJECT_TYPE"),
        }

        result = self.client_graphql.call(query, params)

        output = CheckConfigFilesOutput(result["checkConfigFiles"])

        return output


class CheckConfigFilesOutput(object):
    def __init__(self, result: dict) -> None:
        self.success = result["success"]
        self.reason = result["reason"]


def check_config_files():
    sci_project_type = get_env_variable("SCI_PROJECT_TYPE")
    skip_check_config_files = get_env_variable("SKIP_CHECK_CONFIG_FILES")

    if not skip_check_config_files and sci_project_type not in [
        "DOTNET_APP",
        "DOTNET_LIB",
        "GO_APP",
        "GO_LIB",
    ]:
        graphql_client = GraphqlClient()
        config_files_checker = CheckConfigFiles(graphql_client)

        result = config_files_checker.check()

        if not result.success:
            custom_issues = CustomIssue(graphql_client)
            custom_issues.rule = "SONARQUBE_OR_PROJECT_CONFIG_ARE_WRONG"
            custom_issues.description = (
                "Os arquivos de configuração do Sonar ou do Projeto não estão alinhados. "
                "Verifique os comentários no commit ou MR para mais informações. "
                "Ao corrigir esse problema, pode ocorrer uma queda no coverage. "
                "Qualquer dúvida entre em contato com o time de DevOps."
            )
            custom_issues.notification_text = result.reason

            today = datetime.today()
            next_week = today + timedelta(days=7)

            custom_issues.must_be_fixed_until = next_week

            custom_issues.create()
