""" jinja_variable_name_format_rule.py - Rule class to check that variable names
                                     only use underscores.
"""
from __future__ import annotations

import re
from typing import Any

from j2lint.linter.error import LinterError
from j2lint.linter.rule import Rule
from j2lint.utils import get_jinja_variables

# pylint: disable=duplicate-code


class JinjaVariableNameFormatRule(Rule):
    """Rule class to check that variable names only use underscores."""

    rule_id = "V2"
    description = (
        "If variable is multi-words, underscore `_` should be used "
        "as a separator: '{{ my_variable_name }}'"
    )
    short_description = "jinja-variable-format"
    severity = "LOW"

    regex = re.compile(r"[a-zA-Z0-9-_\"']+[-][a-zA-Z0-9-_\"']+")

    def __init__(self, ignore: bool = False, warn: list[Any] | None = None) -> None:
        super().__init__()

    def checktext(self, filename: str, text: str) -> list[LinterError]:
        raise NotImplementedError

    def checkline(self, filename: str, line: str, line_no: int) -> list[LinterError]:
        """
        Checks if the given line matches the error regex, which matches
        variables using `-` in their name

        Args:
            line (string): a single line from the file

        Returns:
            list[LinterError]: the list of LinterError generated by this rule
        """
        variables = get_jinja_variables(line)
        matches = []
        for var in variables:
            matches = re.findall(self.regex, var)
            matches = [
                match for match in matches if ("'" not in match) and ('"' not in match)
            ]

        return [
            LinterError(line_no, line, filename, self, f"{self.description}: {match}")
            for match in matches
        ]
