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 CheckProjectHealth(object):
    def __init__(self, client_graphql: GraphqlClient = GraphqlClient()) -> None:
        self.client_graphql = client_graphql

    def check(self):
        """Check if project path and project name are the same."""

        query = """
            query checkProjectHealth($projectName: String!, $groupName: String!, $branch: String!) {
                checkProjectHealth(projectName: $projectName, groupName: $groupName, branch: $branch) {
                healthy
                sickness
                projectSickness {
                        reason
                        healthy
                    }
                }
            }
        """

        params = {
            "projectName": get_env_variable_required("CI_PROJECT_NAME"),
            "groupName": get_env_variable_required("CI_PROJECT_NAMESPACE"),
            "branch": get_env_variable_required("CI_COMMIT_REF_NAME"),
        }

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

        output = CheckProjectHealthOutput(result["checkProjectHealth"])

        return output


class CheckProjectHealthOutput(object):
    def __init__(self, result: dict) -> None:
        self.healthy = result["healthy"]
        self.sickness = result["sickness"]


def check_project_health():
    skip_check_project_health = get_env_variable("SKIP_CHECK_PROJECT_HEALTH")

    if not skip_check_project_health:
        graphql_client = GraphqlClient()

        project_health_checker = CheckProjectHealth(graphql_client)

        result_check = project_health_checker.check()

        if not result_check.healthy:
            unhealthy_message = f"{result_check.sickness}"
            custom_issues = CustomIssue(graphql_client)
            custom_issues.rule = "PROJECT_UNHEALTHY"
            custom_issues.description = unhealthy_message
            custom_issues.notification_text = unhealthy_message

            today = datetime.today()
            in_3_days = today + timedelta(days=3)

            custom_issues.must_be_fixed_until = in_3_days

            custom_issues.create()
