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

    def check(self):
        """Check for deprecated primitives on commit"""

        query = """
            query ($projectId: Int!, $commitSha: String!) {
                checkForDeprecatedPrimitives(
                    projectId: $projectId, commitSha: $commitSha
                ) {
                    success
                    reason
                    lastDeprecatedDate
                }
            }
        """

        params = {
            "projectId": int(get_env_variable_required("CI_PROJECT_ID")),
            "commitSha": get_env_variable_required("CI_COMMIT_SHA"),
        }

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

        output = CheckDeprecatedPrimitivesOutput(result["checkForDeprecatedPrimitives"])

        return output


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

        if result["lastDeprecatedDate"]:
            self.last_deprecated_date = datetime.strptime(
                result["lastDeprecatedDate"], "%Y-%m-%d"
            )


def check_deprecated_primitives():
    skip_check_deprecated_primitives = get_env_variable(
        "SKIP_CHECK_DEPRECATED_PRIMITIVES"
    )

    if not skip_check_deprecated_primitives:
        graphql_client = GraphqlClient()

        deprecated_primitives_checker = CheckDeprecatedPrimitives(graphql_client)
        result_check = deprecated_primitives_checker.check()

        if not result_check.success:
            custom_issues = CustomIssue(graphql_client)
            custom_issues.rule = "HAS_DEPRECATED_PRIMITIVES"
            custom_issues.description = (
                "Foi encontrado primitivas deprecadas no projeto."
            )
            custom_issues.notification_text = result_check.reason

            today = datetime.today()
            next_two_week = today + timedelta(days=15)

            must_be_fixed_until = result_check.last_deprecated_date

            if must_be_fixed_until < today or must_be_fixed_until < next_two_week:
                must_be_fixed_until = today + timedelta(days=60)

            custom_issues.must_be_fixed_until = must_be_fixed_until

            custom_issues.create()
